【发布时间】:2015-07-27 20:49:52
【问题描述】:
我编写了一个基本的twisted 服务器,它与一个测试客户端(也在twisted 中)一起工作。
这是服务器:
from twisted.internet import protocol, reactor, endpoints
import pickle
from time import sleep
def function(x, y):
sleep(2)
return x+y
class Pickle(protocol.Protocol):
def dataReceived(self, pickled):
data = pickle.loads(pickled)
response = function(*data)
self.transport.write(pickle.dumps(response))
self.transport.loseConnection()
class PickleFactory(protocol.Factory):
def buildProtocol(self, addr):
return Pickle()
endpoint = endpoints.TCP4ServerEndpoint(reactor, 1234)
endpoint.listen(PickleFactory())
reactor.run()
在客户端,我想要类似的东西
def send(x,y):
'''Calculates function(x,y) on a remote server'''
pass
向服务器发送请求并阻塞,直到它得到响应。我不想在客户端做任何事件驱动/异步的事情。反应堆无法重启的事实意味着我不能天真地为此使用扭曲。
写send 的最佳方式是什么?我可以使用扭曲吗?或者我应该只使用一些低级别的东西,比如 socket 或 telnetlib?
谢谢!
【问题讨论】:
-
不要在网络连接上使用
pickle;它可以执行任意代码。
标签: python sockets tcp twisted