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#客户端文件
具体生成方式参考另外一篇入门文章:《安装Thrift并写一个简单的测试程序》
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自动生成接口)
class HelloWroldImpl : UserStorage.Iface
{
public void store(UserProfile user)
{
throw new NotImplementedException();
}
public UserProfile getUser(int uid)
{
throw new NotImplementedException();
}
}
d.新建HelloWorldServiceClient.cs文件
填写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++ 服务端程序
具体生成方式参考另外一篇入门文章:《安装Thrift并写一个简单的测试程序》
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。