- 本文主要实现 在linux环境下thrift编写服务器/客户端实现图片传输(c++)
代码块
- thrift/send_photo.thrift
service Photo {
bool SendPhoto(1: binary write_buffer, 2: i32 buffer_size)
}
- 命令行 通过thrift生成 cpp文件
# thrift -r --gen cpp send_photo.thrift
- 生成 gen-cpp文件下包括:
send_photo_constants.cpp
send_photo_constants.h
send_photo_types.cpp
send_photo_types.h
Photo.cpp
Photo.h
Photo_server.skeleton.cpp
- 将thrift生成的服务器修改成自己的服务器
# mv Photo_server.skeleton.cpp server.cpp
- 修改server.cpp,只要修改SendPhoto()函数
bool SendPhoto(const std::string& write_buffer, const int32_t buffer_size) {
// Your implementation goes here
printf("SendPhoto\n");
FILE * f = fopen("server.jpg","wb+");
if(f){
fwrite(write_buffer.c_str(),1,buffer_size,f);
fclose(f);
for(unsigned int i = 0; i < 30;i++)
{
printf("%02X ",(unsigned char)write_buffer[i]);
if (i%16 == 15)
{
printf("\n");
}
}
fseek(f,0,SEEK_END);
int size1 = ftell(f);
cout << endl << size1 <<endl;
return true;
}
- 编写client.cpp
#include "Photo.h"
#include <transport/TSocket.h>
#include <transport/TBufferTransports.h>
#include <protocol/TBinaryProtocol.h>
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
using boost::shared_ptr;
int main(int argc, char **argv){
boost::shared_ptr<TSocket> socket(new TSocket("localhost",9090));
boost::shared_ptr<TTransport> transport(new TBufferedTransport(socket));
boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
transport->open();
PhotoClient client(protocol);
char* photo = new char[20];
cout << "input the photo:" << endl;
photo = (char*)malloc(sizeof(char)*20);
scanf("%s",photo);
FILE * f = fopen(photo,"rb");
fseek(f,0,SEEK_END);
int size = ftell(f);
char * buf = new char[size];
memset(buf,0,size);
fseek(f,0,SEEK_SET);
int nRead=fread(buf,sizeof(char),size,f);
bool isRight = client.SendPhoto(string(buf,size),size);
cout << isRight << endl;
transport->close();
return 0;
}
- 编写Makefile
BOOST_DIR = /usr/local/boost/include/boost/
THRIFT_DIR = /usr/local/include/thrift
LIB_DIR = /usr/local/lib
GEN_SRC = captcha_constants.cpp captcha_types.cpp Photo.cpp
default: server client
server: server.cpp
g++ -DHAVE_NETINET_IN_H -o server -I${THRIFT_DIR} -I${BOOST_DIR} -I../gen-cpp -L${LIB_DIR} -lthrift server.cpp ${GEN_SRC}
client: client.cpp
g++ -DHAVE_NETINET_IN_H -o client -I${THRIFT_DIR} -I${BOOST_DIR} -I../gen-cpp -L${LIB_DIR} -lthrift client.cpp ${GEN_SRC}
clean:
$(RM) -r client server
版权声明:本文为qq_26934181原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。