Thrift小試牛刀:實現Windows_C#_客戶端與Linux_C++_服務端通訊
阿新 • • 發佈:2018-12-30
1.下載thrift windows版本
a.官網下載
地址:http://thrift.apache.org/docs/install/windows
如果不需要部署Windows Thrift伺服器,只需要下載原始碼即可。
b.編譯thrift.dll
開啟上圖的工程,編譯Thrift工程,生成thrift.dll(若報錯,需要切換.net框架到4.5)
2.在linux生成C#客戶端檔案
http://blog.csdn.net/ceasadan/article/details/52277136
a.新建demo.thrift檔案,輸入如下內容
struct UserProfile{ 1:i32 id, 2:string name, 3:string blurb } service UserStorage{ void store(1: UserProfile user), UserProfile getUser(1: i32 uid) }
b.輸入C#的Thrift指令,根據demo.thrift檔案生成相應語言的檔案:
thrift -r --gen csharp demo.thrift
如上圖所示生成了UserProfile.cs和UserStorage.cs
3.在Windows vs2013中新建控制檯C#程式
a.引用步驟1中生成的:thrift.dll
b.加入步驟2中生成的:UserProfile.cs和UserStorage.csxx.cs檔案加入到工程
c.新建HelloWroldImpl.cs檔案:引入介面(點選UserStorage.Iface自動生成介面)
d.新建HelloWorldServiceClient.cs檔案class HelloWroldImpl : UserStorage.Iface { public void store(UserProfile user) { throw new NotImplementedException(); } public UserProfile getUser(int uid) { throw new NotImplementedException(); } }
填寫Server的IP和埠
class HelloWorldServiceClient { public const string SERVERIP = "172.16.61.66"; public static int SERVERPORT = 9090; public static int TIMEOUT = 5000; public void startClient(String username) { TTransport transport = null; try { transport = new TSocket(SERVERIP, SERVERPORT, TIMEOUT); //協議要和服務端一致 TProtocol protocol = new TBinaryProtocol(transport); UserStorage.Client client = new UserStorage.Client(protocol); transport.Open(); UserProfile user = new UserProfile(); user.Id = 1; user.Name = "liqb"; user.Blurb = "aaaaaa"; client.store(user); UserProfile user2; user2 = client.getUser(1); Console.WriteLine("Thrift client result =: " ); } catch (Exception e) { Console.WriteLine(e.StackTrace); } finally { if (null != transport) { //close transport.Close(); } } } }
e.main函式新增程式碼,啟動客戶端:
static void Main(string[] args)
{
new HelloWorldServiceClient().startClient("testtxt232");
}
f.啟動程式除錯。
如果報錯被遠端主機拒絕:需要linux關閉防火牆,並且開啟iptables開放埠4.Linux C++ 服務端程式
http://blog.csdn.net/ceasadan/article/details/52277136
5.常見error處理
a.Thrift: Tue Aug 23 17:57:20 2016 TConnectedClient processing exception: Bad version identifier
解決:
協議不一致造成的。服務端是TBinaryProtocol,客戶端是TCompactProtocol。