在Node.js中使用Thrift创建HttpClient

1 投票
1 回答
3010 浏览
提问于 2025-04-18 02:20

我正在使用thrift来实现跨平台的集成。我在thrift中有一个Python服务器。

Python服务器

#!/usr/bin/env python

port = 30303
host = '127.0.0.1'
import sys
sys.path.append('gen-py')

from helloworld import HelloWorld
from helloworld.ttypes import *

from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.transport import THttpClient
from thrift.protocol import TBinaryProtocol
from thrift.protocol import TJSONProtocol
from thrift.server import TServer
from thrift.server import THttpServer

import socket

class HelloWorldHandler:
  def __init__(self):
    self.log = {}

  def sayHello(self):
    print "sayHello()"
    return "say hello from " + socket.gethostbyname(socket.gethostname())    

handler = HelloWorldHandler()
processor = HelloWorld.Processor(handler)
transport = TSocket.TServerSocket(host=host, port=port)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
#pfactory = TJSONProtocol.TJSONProtocolFactory()

#server = THttpServer.THttpServer(processor, (host, port), pfactory)
server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)

print "Starting python server..."
server.serve()
print "done!"

我创建了一个thrift的节点客户端,它可以在Python中创建TSimpleServer时访问Python服务器,但在创建THttpServer时却无法连接。

节点客户端

var thrift = require('thrift');
var ThriftTransports = require('./node_modules/thrift/lib/thrift/transport.js');
var ThriftProtocols = require('./node_modules/thrift/lib/thrift/protocol.js');

var Calculator = require('./gen-nodejs/HelloWorld.js');    
    ttypes = require('./gen-nodejs/helloworld_types.js');    

transport = ThriftTransports.TBufferedTransport()
//protocol = ThriftProtocols.TJSONProtocol()
protocol = ThriftProtocols.TBinaryProtocol()

var connection = thrift.createConnection('127.0.0.1', 30303, {
  transport : transport,
  protocol : protocol
});

connection.on('error', function(err) {
  console.log("error in connection");
  console.error(err);
});

connection.on('connect', function(){    
    var client = thrift.createClient(Calculator,connection);

client.sayHello(function(err, response) {
  console.log(response);
  connection.end();
});
})

我确保在Python中运行THttpServer时使用了JSON协议。不过,我不知道如何在thrift中为节点创建一个HttpClient。

抱歉直接贴代码,但我觉得这样能让问题更清楚。谢谢!

1 个回答

3

Node的HTTP客户端支持是在2014年4月23日添加的。目前这个库的支持只在开发分支上,但不久的将来会和0.9.2版本一起发布。下面是一个使用HTTP节点连接/客户端的示例,服务名称叫做heloSvc:

var thrift = require('thrift');
var helloSvc = require('./gen-nodejs/helloSvc.js');

var options = {
   transport: thrift.TBufferedTransport,
   protocol: thrift.TJSONProtocol,
   path: "/hello",
   headers: {"Connection": "close"}
};

var connection = thrift.createHttpConnection("localhost", 9090, options);
var client = thrift.createHttpClient(helloSvc, connection);

client.getMessage("Thurston Howell", function(error, result) {
  console.log("Msg from server: " + result);
});

撰写回答