利用Thrift使Java与C#进行通信

步骤1.下载thrift-0.11.0.tar.gz文件,解压缩。链接:http://www.apache.org/dyn/closer.cgi?path=/thrift/0.11.0/thrift-0.11.0.tar.gz
步骤2.下载thrift.exe文件,加入到thrift根目录下。链接:http://thrift.apache.org/download
步骤3. 在根目录下新建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)  
} 

若传输文件,创建Interface.thrift文件,内容如下:

struct FileData  
{  
    1:required string   name,                   // 文件名字  
    2:required binary   buff,                   // 文件数据  
}  

Service

service FileInfoExtractService  
{  
    bool uploadFile(1:FileData filedata);       // 文件解析函数  
} 

步骤4. 打开doc窗口,进入thrift所在的目录,输入thrift-0.11.0.exe -r -gen java(或csharp) domo.thrift。文件夹中自动生成一个名字为gen-java(或gen-csharp)的文件夹,下面就是生成的java(或csharp)文件。
步骤5. 客户端:
C#客户端:thrift-0.11.0\lib\csharp\src\Thrift.sln 编译,即可生成Thrift.dll文件,要在C#客户端项目中依赖该文件。步骤4中生成的.cs文件加入到项目中。
数据传输时ClientApp.cs文件写法:

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

namespace ThriftTest
{
    class ClientApp
    {
        static void Main(string[] args)
        {
            TTransport transport = new TSocket("localhost", 8899);
            TProtocol protocol = new TBinaryProtocol(transport);
            test.Hello.Client client = new test.Hello.Client(protocol);
            transport.Open();
            Console.WriteLine("Client calls client.helloString().....");
            Console.WriteLine(client.helloString("jiyiqin"));
            client.Dispose();
        }
    }
}

文件传输时,ClientApp .cs文件写法:

using System;
using Thrift.Transport;
using Thrift.Protocol;
using System.IO;

class ClientApp 
{
    static void Main(string[] args)
    {
         String filePath = "D://fruit.jpg";
        FileData fileData = new FileData();
        byte[] bytes = set(filePath);
        fileData.Name = filePath;
        fileData.Buff = bytes;
        try
        {
            TSocket transport = new TSocket("localhost", 12345);
            TFramedTransport framedTransport = new TFramedTransport(transport);
            Console.WriteLine("fdsfs");
            framedTransport.Open();
            TBinaryProtocol binaryProtocol = new TBinaryProtocol(framedTransport);
            FileService.Client client = new FileService.Client(binaryProtocol);
            client.uploadFile(fileData);
        }
        catch (Exception x)
        {
            Console.WriteLine("错了");
        }
        Console.ReadLine();
    }
  }
private static byte[] set(String filePath)     //创建set函数
{
    FileInfo fileInfo = new FileInfo(filePath);
    byte[] b = new byte[fileInfo.Length];
    FileStream fs = new FileStream(filePath,FileMode.Open,FileAccess.Read);
    fs.Read(b,0,b.Length);
    fs.Close();
    GC.ReRegisterForFinalize(fileInfo);
    GC.ReRegisterForFinalize(fs);
    return b;
}

java客户端:thrift-0.11.0\lib\java(包含build.xml),通过ant命令生成jar文件,新建项目,导入libthrift-0.11.0.jar
数据传输时ClientApp .java文件写法:

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
public class ClientApp {
    public static final String SERVER_IP = "localhost";
    public static final int SERVER_PORT = 8899;
    public static final int TIMEOUT = 30000;
    public static void main(String[] args) {
        Client client = new Client();
        client.startClient("amosli");
    }
    public void startClient(String userName) {
        userName ="jiaqian";
        TTransport transport = null;
        String result = null;
        try {
            transport = new TSocket(SERVER_IP, SERVER_PORT, TIMEOUT);
            // 协议要和服务端一致
            TProtocol protocol = new TBinaryProtocol(transport);
            // TProtocol protocol = new TJSONProtocol(transport);
            Hello.Client client = new Hello.Client(protocol);
            transport.open();
            result = client.helloString(userName);
            System.out.println("Thrift client result =: " + result);
        } 
catch (TTransportException e) {
            e.printStackTrace();
        } catch (TException e) {
            e.printStackTrace();
        } finally {
            if (null != transport) {
                transport.close();
            }
        }
    }
}

文件传输时ClientApp.java文件写法:

import org.apache.thrift.protocol.TBinaryProtocol;  
import org.apache.thrift.transport.TFramedTransport;  
import org.apache.thrift.transport.TSocket;  
import java.io.ByteArrayOutputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.nio.ByteBuffer;  
public class ClientApp
{  
    public static void main(String[] args)  
    {  
        // 测试文件路径  
        String filePath = "D:\\fruit.jpg";  
        // 构造文件数据  
        byte[] bytes = toByteArray(filePath);  
        FileData fileData = new FileData();  
        fileData.name = filePath;  
        fileData.buff = ByteBuffer.wrap(bytes);  
        // 构造Thrift客户端,发起请求  
        try  
        {  
            TSocket socket = new TSocket("localhost", 12345);  
            socket.setSocketTimeout(60 * 1000);  
            TFramedTransport framedTransport = new TFramedTransport(socket);  
            framedTransport.open();  
            TBinaryProtocol binaryProtocol = new TBinaryProtocol(framedTransport);  
            FileService.Client client = new FileService.Client(binaryProtocol);  
            client.uploadFile(fileData);  
        }  
        catch (Exception x)  
        {  
            x.printStackTrace();  
        }
    }  
    /** 
     * 文件转化为字节数组 
     * */  
    private static byte[] toByteArray(String filePath){  
        byte[] buffer = null;  
        try {  
            File file = new File(filePath);  
            FileInputStream fis = new FileInputStream(file);  
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);  
            byte[] b = new byte[1000];  
            int n;  
            while ((n = fis.read(b)) != -1) {  
                bos.write(b, 0, n);  
            }  
            fis.close();  
            bos.close();  
            buffer = bos.toByteArray();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }
        return buffer;  
    }  
}  

步骤6. java服务端:
传输数据时ServiceApp.java文件写法:

import org.apache.thrift.protocol.TBinaryProtocol;     
import org.apache.thrift.protocol.TBinaryProtocol.Factory;     
import org.apache.thrift.server.TServer;     
import org.apache.thrift.server.TThreadPoolServer;     
import org.apache.thrift.server.TThreadPoolServer.Args;     
import org.apache.thrift.transport.TServerSocket;     
import org.apache.thrift.transport.TTransportException;
import com.jiaqian.thirft.Hello.Processor;   
public class ServiceApp {   
   @SuppressWarnings({"rawtypes", "unchecked" })  
    public String startServer() {     
        try {     
            System.out.println("thrift server host on port 8899");   
            TServerSocket serverTransport = new TServerSocket(8899);  
            Hello.Processor process = new Processor(new HelloImpl());     
            Factory portFactory = new TBinaryProtocol.Factory(true, true);     
            Args args = new Args(serverTransport);     
            args.processor(process);
            args.protocolFactory(portFactory);     
            TServer server = new TThreadPoolServer(args);     
            server.serve();   
        } catch (TTransportException e) {
            e.printStackTrace();
        }
        return "thrift server host on port 8899";    
   }
   public static void main(String[] args) {      
        System.out.println("thrift server init");   
        Server server = new Server();
        System.out.println("thrift server start");   
        server.startServer();     
        System.out.println("thrift server end");   
   }     
}   

传输数据时HelloImp.java写法:

import org.apache.thrift.TException;
import com.jiaqian.thirft.Hello.Iface;  

public class HelloImpl implements Iface{   
   private static int count= 0;        
   @Override   
   public String helloString(String word)throws TException  
   {  
        count += 1;   
        System.out.println("get " + word + " " +count);    
        return "hello " + word + " " + count;   
   }    
}  

传输文件时ServiceApp.java文件写法

import org.apache.thrift.TProcessor;  
import org.apache.thrift.protocol.TBinaryProtocol;  
import org.apache.thrift.server.TServer;  
import org.apache.thrift.server.TThreadedSelectorServer;  
import org.apache.thrift.transport.TFramedTransport;  
import org.apache.thrift.transport.TNonblockingServerSocket;  
import org.apache.thrift.transport.TNonblockingServerTransport;  
import org.apache.thrift.transport.TTransportFactory;  

public class ServiceApp
{  
    public static void main(String[] args)  
    {  
        try  
        {  
            // 创建非阻塞的 Transport  
            TNonblockingServerTransport serverSocket = new TNonblockingServerSocket(12345);  
            // 创建 Processor  
            TProcessor processor = new FileService.Processor(new FileServiceImpl());  
            // 创建 transport factory , Nonblocking 使用 TFramedTransport  
            TTransportFactory transportFactory = new TFramedTransport.Factory();  
            // 创建 protocol factory  
            TBinaryProtocol.Factory protocolFactory = new TBinaryProtocol.Factory();  
            // 创建 arguments  
            TThreadedSelectorServer.Args tArgs = new TThreadedSelectorServer.Args(serverSocket);  
            tArgs.processor(processor);  
            tArgs.transportFactory(transportFactory);  
            tArgs.protocolFactory(protocolFactory);  
            // 创建 server  
            TServer server = new TThreadedSelectorServer(tArgs);  
            // 启动 server  
            server.serve();  
        }  
        catch (Exception x)  
        {  
            x.printStackTrace();  
        }  
    }  
}  

传文件时java的FileServiceImpl.java文件写法:

import org.apache.thrift.TException;
import java.io.FileOutputStream;  
import java.nio.channels.FileChannel;  
public class FileServiceImpl implements FileService.Iface  
{  
    int i=1;
    @Override  
    public boolean uploadFile(FileData filedata) throws TException  
    {  
        System.out.println("uploadFile function has been called.");  
        i++;
        // 写到文件  
        String filePath = "D:\\fruit"+i+".jpg";  
        try  
        {  
            java.io.File file = new java.io.File(filePath);  
            FileOutputStream fos = new FileOutputStream(file);  
            FileChannel channel = fos.getChannel();  
            channel.write(filedata.buff);  
            channel.close();  
        }  
        catch (Exception x)  
        {  
            x.printStackTrace();  
            return false;  
        }  
        return true;  
    }  
}  
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值