【发布时间】:2018-03-13 19:52:43
【问题描述】:
我有来自 twisted 的客户端/服务器代码示例。现在,我的要求是,当从客户端调用服务器时 - 服务器将调用推迟到一个线程,该线程实际上回复客户端,服务器可以做其他事情。简单来说,假设客户端 C1 使用模板 Temp1 调用服务器 S1。服务器将其推迟到线程 T1。 T1 现在必须处理函数 A、B 和 C,最后返回客户端 C1。下面是我的服务器代码。
我是 twisted 的新手,我收到错误:Deferred 中的未处理错误:
from twisted.internet import reactor, protocol, threads
def foo():
time.sleep(5)
print('Hello how are you!!!!')
def print_result():
print('Processing done!!')
def onError():
print('Error!!!!')
class Echo(protocol.Protocol):
"""This is just about the simplest possible protocol"""
def process_func(self, data):
print('hello i am in process_func!!!')
self.transport.write(data)
return foo()
def onErrorfunc(self):
onError()
def onProcessDone(self):
print_result()
def dataReceived(self, data):
"As soon as any data is received, write it back."
# thr = threading.Thread(target=foo, args=(), kwargs={})
# thr.start()
d = threads.deferToThread(self.process_func, *data)
d.addCallback(self.onProcessDone)
d.addErrback(self.onErrorfunc)
# do something else here
# self.transport.write(data)
def main():
"""This runs the protocol on port 8000"""
factory = protocol.ServerFactory()
factory.protocol = Echo
reactor.listenTCP(8000,factory)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
为什么是twisted,因为客户端/服务器已经用twisted编写了,我正在做一些小的改动。帮助表示赞赏。谢谢!
【问题讨论】:
标签: python twisted twisted.web twisted.internet