1

我正在使用 Thrift 进行跨平台集成。我有一个节俭的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 协议。我不知道如何在节俭中为节点创建 HttpClient。

很抱歉转储代码,但我认为它会使问题更清楚。谢谢

4

1 回答 1

3

Node http 客户端支持于 2014 年 4 月 23 日添加。该库支持目前仅在 dev 分支中,但将在不久的将来与 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);
});
于 2014-04-13T04:25:59.537 回答