编译C++库
1.解压安装包,然后打开thrift0.13.0\lib\cpp 路径下的thrift.sln工程
将 boost,libevent ,openssl, zlib 的头文件和库路径添加到工程上
2.然后工程中可能与实际目录不匹配,所以还需要修改
把src\thrift\concurrency\Util.cpp这个路径不匹配,移除该文件
3.宏定义加上PACKAGE_VERSION THRIFT_STATIC_DEFINE
除了boost 其他的都是可选,可在工程中对相关cpp文件进行添加和删除
再运行用vs直接编译即可
用例
编写./trhift文件
namespace cpp Sample
struct Data{
1:i32 i,
2:i32 num
}
service SampleServer
{
i32 showNum(1:Data d)
}
在命令行下输入
thrift-0.13.0 -r --gen cpp sample/a/sample.thrift
运行之后生成gen-cpp的文件夹
VS创建用例工程-参考一下截图
每个工程配置好thrift的库 openssl的等的头文件路径,库路径以及库。
服务器端主函数代码SampleServer_server.skeleton.cpp,我这边基本上没有改动
#include <thrift/server/TSimpleServer.h>
#include <thrift/transport/TServerSocket.h>
#include <thrift/transport/TBufferTransports.h>
using namespace ::apache::thrift;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::server;
using namespace ::Sample;
class SampleServerHandler : virtual public SampleServerIf {
public:
SampleServerHandler() {
// Your initialization goes here
}
int32_t showNum(const Data& d) {
// Your implementation goes here
printf("showNum i:%d num:%d\n",d.i, d.num);
return 0;
}
};
int main(int argc, char **argv) {
int port = 9090;
::std::shared_ptr<SampleServerHandler> handler(new SampleServerHandler());
::std::shared_ptr<TProcessor> processor(new SampleServerProcessor(handler));
::std::shared_ptr<TServerTransport> serverTransport(new TServerSocket(port));
::std::shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());
::std::shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory);
server.serve();
return 0;
}
client.cpp
#include "SampleServer.h"
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/server/TSimpleServer.h>
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TBufferTransports.h>
using namespace ::apache::thrift;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::server;
using namespace ::Sample;
class SampleServerHandler : virtual public SampleServerIf {
public:
SampleServerHandler() {
// Your initialization goes here
}
int32_t showNum(const Data& d) {
// Your implementation goes here
printf("showNum\n");
}
};
int main(int argc, char **argv) {
int port = 9090;
int ret = 0;
Data d;
d.i = 1;
d.num = 2;
::std::shared_ptr<TSocket> socket(new TSocket("127.0.0.1", port));
::std::shared_ptr<TBufferedTransport>transport(new TBufferedTransport(socket));
::std::shared_ptr<TBinaryProtocol> protocol(new TBinaryProtocol(transport));
SampleServerClient clinet(protocol);
transport->open();
ret = clinet.showNum(d);
printf("ret:%d\n", ret);
transport->close();
return 0;
}
编译好之后,线运行server, 再运行client。
运行效果
服务器端
客户端:
抓包可以插卡具体数据