Example
1).thrift
struct Student{
1: i32 sno,
2: string sname,
3: bool ssex,
4: i16 sage,
}
service Serv{
void put(1: Student s),
}
2)自动生成文件
thrift -r --gen cpp student.thrift
3)修改.skeleton.cpp
class ServerServiceHandler : virtual public ServerServiceIf {
public:
ServerServiceHandler() {
// Your initialization goes here
//这里写初始化
//构造函数
printf("Initialize\n");
}
void show(const Student& student) {
// Your implementation goes here
//这里写需要实现的服务
//用于处理客户端传送来的参数
printf("show\n");
//用printf写一个简单的数据处理服务
printf("ID = %d Name = %s Sex = %d Age = %d/n", s.ID, s.Name.c_str(), s.Sex, s.Age);
}
};
4)使用thrift包自动生成的client类来实现客户端
就是用来调用client类就可以了,真正的client功能其实已经实现了
#include "ServerService.h"
#include <transport/TSocket.h>
#include <transport/TBufferTransports.h>
#include <protocol/TBinaryProtocol.h>
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();
Student student;
s.ID = 2016220102031;
s.Name = "WYZ";
s.Sex = 1;
s.sage = 22;
ServerServiceClient client(protocol);
client.put(student);
transport->close();
return 0;
}