您的位置:首页 > 编程语言 > Java开发

C#使用Thrift简介,C#客户端和Java服务端相互交互

2014-09-01 15:30 549 查看
C#使用Thrift简介,C#客户端和Java服务端相互交互

本文主要介绍两部分内容:

C#中使用Thrift简介

用Java创建一个服务端,用C#创建一个客户端通过thrift与其交互。

用纯C#实现Client和Server

其中使用到RPC学习----Thrift快速入门和Java简单示例,这篇文章创建的Java服务端。

一、C#中使用Thrift简介

关于rpc的简介,可以参考:RPC学习----Thrift快速入门和Java简单示例

1、下载thrift

1)点击下载:thrift-0.9.1.tar.gz (或者http://thrift.apache.org/download)

2)Thrift compiler for Windows (thrift-0.9.1.exe)

两个都要下载。

2、引入thrift.dll

这里将下载好的.gz文件解压后,然后找到lib目录



用vs打开后,如下图所示,然后右键--》重新生成---》生成thrift.dll





3、生成cs文件

hello.thrift

service  HelloWorldService {
string sayHello(1:string username)
}


使用命令生成cs文件:

thrift-0.9.1.exe -gen csharp hello.thrift




关于thrift-0.9.1.exe的使用方法可以查看命令: [b]thrift-0.9.1.exe -help[/b]



将生成的HelloWorldService.cs文件拷入项目中。

二、C#客户端发送消息到Java生成的服务端,实现跨平台操作

1、启动Java版的服务端



2、使用vs新建一个winform程序



button点击事件:

private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != null)
{
new HelloWorldServiceClient().startClient(textBox1.Text.Trim());
}
}


HelloWorldServiceClient.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Thrift.Protocol;
using Thrift.Transport;
using Thrift;

namespace thrfitCsharp
{
class HelloWorldServiceClient
{
public const string SERVERIP = "localhost";
public static int SERVERPORT = 8090;
public static int TIMEOUT = 3000;

public void startClient(String username)
{
TTransport transport = null;
try
{
transport = new TSocket(SERVERIP, SERVERPORT, TIMEOUT);
//协议要和服务端一致
TProtocol protocol = new TCompactProtocol(transport);
HelloWorldService.Client client = new HelloWorldService.Client(protocol);
transport.Open();
String result = client.sayHello(username);
Console.WriteLine("Thrift client result =: " + result);

}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
finally
{
if (null != transport)
{
//close
transport.Close();
}
}
}

}
}


HelloWroldImpl.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace thrfitCsharp
{
class HelloWroldImpl : HelloWorldService.Iface
{

public  string sayHello(string username){
Console.WriteLine("hello"+username);
return "hello" + username;
}

}
}


效果图:



注:下面是改进版的,主要添加了纯C#版的:



纯C#版是说用C#实现客户端和服务端,下面是纯c#版的输出:



本文源码https://github.com/amosli/rpc/tree/thriftCsharp

纯C#版实现主要参考http://www.cnblogs.com/hanmos/archive/2011/09/15/2177891.html

分类: other, C#, java学习
标签: C#, C# 使用Thrift简介, C#客户端和Java服务端相互交互, Thrift
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: