在扭曲的延迟线程中未处理的错误



我有来自扭曲的客户端/服务器代码示例。现在,我的要求是,当从客户端调用服务器时 - 服务器将调用推迟到线程,线程实际上回复客户端,服务器可以执行其他操作。简而言之,假设客户端 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()
为什么扭曲,

因为客户端/服务器已经写成扭曲了,我正在做一些小的更改。感谢帮助。谢谢!

很难

说出你的Unhandled error in 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(),因为它是使用 扭曲reactor 调度的。而是在线程中的计算完成后在回调中运行它。线程应该只用于密集计算,因为 Twisted 为您提供了大量选项,可以在单个线程中高效运行代码。

最新更新