thrift cpp環境搭建:
1、 安裝boost_1_53_0,注意,使用vs2010版本時,使用二進制的boost安裝版本,生成的lib有可能是,在后續操作會出問題。在源碼目錄中,運行bootstrap.dat,然后會生成b2.exe文件,該文件可以編譯boost需要的庫,生成文件在boost\stage\lib文件下,后續對於lib的添加使用該路徑。
2、 網絡下載Win64OpenSSL_Light-1_1_0f.exe、Win64OpenSSL- 1_1_0f.exe,可以選擇安裝后者,前者是輕量級的不含源碼的目標文件。
3、 下載thrift-0.9.0源碼以及編輯器。打開thrift-0.9.0\thrift-0.9.0\lib\cpp中sln工程,編譯libthrift工程和libthriftnb工程。前者為阻塞的,后者為非阻塞模式的服務器,非阻塞模式的服務器需要libevent庫。
4、 對與編譯libthrift工程,添加依賴頭文件(C/C++ - general – Additional include directories):
C:\local\boost_1_53_0
C:\OpenSSL-Win64\include
添加依賴的鏈接庫:(Linker – general – Additional library directories)
C:\local\boost_1_53_0\stage\lib
build該工程,會在debug文件夾中生成后續需要的libthrift.lib文件。
5、 對於寫好的接口文件helloworld.thrift,通過命令行生成對應的接口文件,文件在gen-cpp中,其中含有HelloWorld_server.skeleton.cpp為服務器框架。
6、 通過vs2010創建空項目,添加gen-cpp中的頭文件與資源文件,添加boost庫的依賴頭文件以及lib方法同上,添加thrift的相關文件為:
include項:C:\Users\Administrator\Desktop\thrift-0.9.0\thrift-0.9.0\lib\cpp\src
lib項:C:\Users\Administrator\Desktop\thrift-0.9.0\thrift-0.9.0\lib\cpp\Debug
此時編譯可能出現“error LNK2019”,無法解析的外部符號,此問題由於缺少相應的庫文件,解決方法為:Linker – input – Additional dependencies 添加libthrift.lib即可。
編譯過程可能出現語句報錯,譬如會有:using namespace ; 這種語句,注釋掉即可。
7、 此時可以編譯通過,但是會出錯:
此時,在生成得到服務器框架的cpp中main函數中添加TWinsockSingleton::create();即可,在高版本的thrift已經不需要這一句了。
再次運行即可。
打開之前python的客戶端,設置好端口,運行即可在服務器看到通信結果。
服務器的編寫可以在生成的框架下進行修改,客戶端的編寫為:
#include "HelloWorld.h" #include <thrift\transport\TSocket.h> #include <thrift\transport\TBufferTransports.h> #include <thrift\protocol\TBinaryProtocol.h> #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 boost::shared_ptr; #include <iostream> int main(int argc,char **argv) { shared_ptr<TSocket> socket(new TSocket("127.0.0.1",9090)); shared_ptr<TTransport> transport(new TBufferedTransport(socket)); shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport)); HelloWorldClient client(protocol); try { transport->open(); } catch(TTransportException) { transport->close(); } client.ping(); std::string s; client.sayHello(s); std::cout<<s<<std::endl; getchar(); return 0; }
如上,其中sting的返回值需要修改服務器中sayHello對應函數,使得s獲得一個返回值。
客戶端工程同樣需要添加以來庫,同時將gen-cpp中的文件(除服務器框架文件)拷到目錄下,添加到項目中。
Thrift 采用C/S模型,不支持雙向通信,為了解決這個問題,通常在通信雙方建立兩個通信通道,開兩個端口。