1.下载Thrift
http://apache.fayea.com/apache-mirror/thrift/0.9.2/thrift-0.9.2.tar.gz
2.下载编译器并解压
http://www.apache.org/dyn/closer.cgi?path=/thrift/0.9.2/thrift-0.9.2.exe
3.设置编译器的路径为环境变量
我的thrift-0.9.2.exe 放在C:/Windows路径下,所以设置环境变量中的 path:为 C:\Windows;
4.编写一个 test.thrift 文件
namespace java com.javabloger.gen.code struct User { 1: i32 ID 2: string Name } service UserService { User GetUserByID(1:i32 userID) list<User> GetAllUser() }
5.根据thrift自动生成Csharp代码
cmd中路径指定到test.Thrift的路径, 执行命令 thrift --gen csharp test.thrift
就会自动生成gen-csharp文件夹,里面有2个文件 User.cs 和 UserService.cs
6.新建工程
MyInterface中加入刚自动生成的文件
MyServer
class="code_img_closed" src="/Upload/Images/2014112512/0015B68B3C38AA5B.gif" alt="" />logs_code_hide('9562bdfd-b935-48b9-92ac-b6529df15cc3',event)" src="/Upload/Images/2014112512/2B1B950FA3DF188F.gif" alt="" />class Program { static void Main(string[] args) { TServerSocket serverTransport = new TServerSocket(8899, 0, false); UserService.Processor processor = new UserService.Processor(new MyUserService()); TServer server = new TSimpleServer(processor, serverTransport); Console.WriteLine("Starting server on port 8899 ..."); server.Serve(); } } public class MyUserService : UserService.Iface { public User GetUserByID(int userID) { return new User() { ID = 1, Name = "wangxm" }; } public List<User> GetAllUser() { List<User> users = new List<User>(){ new User() { ID = 1, Name = "wangxm" }, new User() { ID = 2, Name = "xxxx" } }; return users; } }View Code
MyClient
static void Main(string[] args) { TTransport transport = new TSocket("localhost", 8899); TProtocol protocol = new TBinaryProtocol(transport); UserService.Client client = new UserService.Client(protocol); transport.Open(); var users = client.GetAllUser(); users.ForEach(u => Console.WriteLine(string.Format("User ID : {0}, User Name {1}", u.ID, u.Name))); var user = client.GetUserByID(1); Console.WriteLine("------------------"); Console.WriteLine(string.Format("User ID : {0}, User Name {1}", user.ID, user.Name)); Console.ReadLine(); }View Code
7:运行结果如下