概要
- 在服务端定义一个myStruct结构体,实现一个void sayhello(myStruct)函数;在客户端进行远程调用。
Struct myStruct{
1:string name,
2:string mystr,
}
Void void sayhello(myStruct)
{
printf("sayhello\n");
}
具体步骤如下
1. 创建MyService.thrift文件
2.编写MyService.thrift脚本
3.生成工程文件
用如下thrift命令自动生成远程调用工程与服务端代码
thrift --gen cpp MyService.thrift
–gen cpp表示生成C++语法的数据。运行后会自动生成一个gen-cpp文件夹,里面包含的内容如下:
- MyService_server.skeleton.cpp为服务端代码,内容如下:
你的服务端程序可以写在图中画横线的位置。
4.编写客户端程序
-
- touch client.cpp,创建client.cpp
-
- client.cpp内容如下:
// This autogenerated skeleton file illustrates how to build a server.
// You should copy it to another filename to avoid overwriting it.
#include "MyService.h"
#include <thrift/protocol/TBinaryProtocol.h>
//#include <thrift/server/TSimpleServer.h>
//#include <thrift/transport/TServerSocket.h>
#include <thrift/transport/TBufferTransports.h>
#include<iostream>
#include <thrift/transport/TSocket.h>
using namespace ::apache::thrift;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::transport;
//using namespace ::apache::thrift::server;
using namespace std;
int main(int argc, char **argv) {
std::shared_ptr<TSocket>socket(new TSocket("localhost",9090));
std::shared_ptr<TTransport>transport(new TBufferedTransport(socket));
std::shared_ptr<TProtocol>protocol(new TBinaryProtocol(transport));
transport->open();
MyServiceClient client(protocol);
myStruct mydata;
mydata.name="xiaoming";
mydata.mystr="testdata";
std::cout<<"\nclient send a data !\n "<<std::endl;
client.sayhello(mydata);
std::cout<<"\nclient send a data ending !\n "<<std::endl;
transport->close();
return 0;
}
5.编译
分别运行下面两条命令生成 server与cli两个可执行文件
g++ -g -lthrift MyService.cpp MyService_types.cpp client.cpp.cpp -o cli
g++ -g -lthrift MyService.cpp MyService_types.cpp MyService_server.skeleton.cpp -o server
6测试
- 先运行服务器./server,再运行客户端./cli,结果如下图所示表示成功。
欢迎评论
还想学点儿什么呢!