我有来自twisted的客户端/服务器代码示例。现在,我的要求是,当从客户端对服务器进行调用时,服务器将调用推迟到线程,该线程实际上回复客户端,并且服务器可以执行其他操作。简而言之,假设客户端 C1 使用模板 Temp1 调用服务器 S1。服务器将其推迟到线程 T1。 T1 现在必须处理函数 A、B 和 C,并最终返回客户端 C1。下面是我的服务器代码。
我是扭曲的新手,我收到错误:延迟中未处理的错误:
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编写了,我正在做一些小的改变。感谢帮助。谢谢!
最佳答案
很难判断您的 Deferred 中未处理的错误
源于何处,因为您的示例充满了语法错误,但我会尝试使用我的直觉并重写您想要执行的操作:)。我已经发表了一些评论,所以请看一下您的代码和此代码有何不同。
import time
from twisted.internet import reactor, protocol, threads
def foo():
# this function didn't return anything in your example
# now it returns a string
time.sleep(5)
return 'Hello how are you!!!!'
class Echo(protocol.Protocol):
def process_func(self, data):
# data is unused here, typically you would "do something" to data in a thread
# remember data is a bytes type not string!
print('hello i am in process_func!!!')
return foo()
def onErrorfunc(self, failure):
print('Error: {0}'.format(failure.value))
def onProcessDone(self, result):
# result is the string returned from process_func()
# if Python version >= 3 then transport.write arg must be bytes
self.transport.write(result.encode('utf8'))
print('Processing done!!')
def dataReceived(self, data):
d = threads.deferToThread(self.process_func, data)
d.addCallback(self.onProcessDone)
d.addErrback(self.onErrorfunc)
尽量不要在线程中使用 self.transport.write()
,因为它是使用 Twisted reactor
进行调度的。相反,在线程中的计算完成后,在回调中运行它。线程只能用于密集计算,因为 Twisted 为您提供了大量在单个线程中高效运行代码的选项。
关于python - 扭曲 deferToThread 中的延迟中未处理的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49264788/