下面要與大家分享的是使用 node.js 當 client 連接 go 的server。 之前已經試過使用 go client 和 java client 去連go server,原本以為因該是很容易就可以測試成功,沒想到光是想成功用 node.js連上 go server就讓我卡關一天。最後發現原因竟然是因為 transport 和 protocol 的選擇造成,在此分享可以實作成功的組合。

  • golang server
 transportFactory := thrift.NewTTransportFactory()
 protocolFactory := thrift.NewTBinaryProtocolFactoryDefault()
 transportFactory = thrift.NewTBufferedTransportFactory(8192)
 handler := rpcService.NewAdminRPCHandler()
 processor := rpc.NewRpcServiceProcessor(handler)
 serverTransport, err := thrift.NewTServerSocket(settings.Get().RPCAddr)
 if err != nil {
 Logger.Info("Starting RPC server error :%s", err)
 os.Exit(1)
 }
 server := thrift.NewTSimpleServer4(processor, serverTransport, transportFactory, protocolFactory)
 go server.Serve()
 

 

  • node.js client
    • 建立node.js 版本服務定義檔: thrift –gen js:node RpcService.thrift
    • 安裝 thrift的 node.js版 library: sudo npm install -g thrift
var thrift = require('thrift');
var transport = thrift.TBufferedTransport();
var protocol = thrift.TBinaryProtocol();
var service = require('./gen-nodejs/RpcService.js');
var ttypes = require('./gen-nodejs/RpcService_types.js');
var connection = thrift.createConnection("localhost", 9090, {
    transport : transport,
    protocol : protocol
});
connection.on('error', function(err) {
 console.log(err)
});
var client = thrift.createClient(service, connection);
client.GoogleSnapToRoad("25.111,121.222", function(err, response) {
if(err){
    return console.log(err)
}
});