我试图通过一个简单的例子来学习Thrift(版本0.9.2)如何在python中运行。服务器代码工作正常,但运行客户端代码会出现错误Could not connect to localhost:9090
,我尝试了shell命令
netstat -nap | grep 9090
,此输出
tcp 0 0 0.0.35.130:9090 0.0.0.0:* LISTEN 4656/python
,
和命令
nc -zv localhost 9090
输出
nc: connect to localhost port 9090 (tcp) failed: Connection refused
。
此时我不确定哪个部分(计算机本身,Thrift或代码?)出错了。所有代码都给出如下,有人会指出错误在哪里吗?
以下是helloworld.thrift
:
const string HELLO_IN_KOREAN = "an-nyoung-ha-se-yo"
const string HELLO_IN_FRENCH = "bonjour!"
const string HELLO_IN_JAPANESE = "konichiwa!"
service HelloWorld {
void ping(),
i32 sayHello(),
i32 sayMsg(1:string msg)
}
,服务器代码是,
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.protocol import TBinaryProtocol
from thrift.server import TServer
import socket
class HelloWorldHandler:
def __init__(self):
self.log = {}
def ping(self):
print "ping()"
def sayHello(self):
print "sayHello()"
return "say hello from " + socket.gethostbyname()
def sayMsg(self, msg):
print "sayMsg(" + msg + ")"
return "say " + msg + " from " + socket.gethostbyname()
handler = HelloWorldHandler()
processor = HelloWorld.Processor(handler)
transport = TSocket.TServerSocket('9090')
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
print "Starting python server..."
server.serve()
print "done!"
这是客户端,
import sys
sys.path.append('../gen-py')
from helloworld import HelloWorld
from helloworld.ttypes import *
from helloworld.constants import *
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
try:
# Make socket
transport = TSocket.TSocket('localhost', 9090)
# Buffering is critical. Raw sockets are very slow
transport = TTransport.TBufferedTransport(transport)
# Wrap in a protocol
protocol = TBinaryProtocol.TBinaryProtocol(transport)
# Create a client to use the protocol encoder
client = HelloWorld.Client(protocol)
# Connect!
transport.open()
client.ping()
print "ping()"
msg = client.sayHello()
print msg
msg = client.sayMsg(HELLO_IN_KOREAN)
print msg
transport.close()
except Thrift.TException, tx:
print "%s" % (tx.message)
答案 0 :(得分:4)
我认为问题在于你的电话 -
transport = TSocket.TServerSocket('9090')
这应该是
transport = TSocket.TServerSocket(host='localhost', port=9090)
或
transport = TSocket.TServerSocket(port=9090)
实际上 - 甚至不需要port
参数。如果你不给,它的默认值是9090.你的代码是说主持人是9090
这可以从netstat -nap
输出中清楚地看出。这条线确实显示了一些东西'监听端口9090(这是因为thrift TServerSocket中的默认端口是9090),但检查侦听地址,它是0.0.35.130
。任何界面都应为0.0.0.0
,127.0.0.1
为localhost
。
编辑:
事实上,如果你做socket.getaddrinfo('9090', 9090)
。它确实显示了0.0.35.130
的地址,因此您在netstat
中看到的内容并不令人惊讶。
您的nc
输出也表示没有正在侦听localhost:9090
(通过连接拒绝错误)。
上述修复应解决问题。