.net Thrift 之旅 (一) Windows 安装及 HelloWorld

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.新建工程

     .net Thrift 之旅 (一) Windows 安装及 HelloWorld

  MyInterface中加入刚自动生成的文件

  MyServer 

.net Thrift 之旅 (一) Windows 安装及 HelloWorld
   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

.net Thrift 之旅 (一) Windows 安装及 HelloWorld
 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:运行结果如下

.net Thrift 之旅 (一) Windows 安装及 HelloWorld

.net Thrift 之旅 (一) Windows 安装及 HelloWorld

上一篇:基于c#的工控软件版本v1.01_11.25


下一篇:Js 实现 C# Format方法