我有一个服务器,我在其中实现了 NetstringReceiver 协议(protocol)的子协议(protocol)。我希望它根据客户端的请求执行异步操作(使用 txredisapi),然后响应操作结果。我的代码的概括:
class MyProtocol(NetstringReceiver):
def stringReceived(self, request):
d = async_function_that_returns_deferred(request)
d.addCallback(self.respond)
# self.sendString(myString)
def respond(self, result_of_async_function):
self.sendString(result_of_async_function)
在上面的代码中,连接到我的服务器的客户端没有得到响应。但是,如果我取消注释,它确实会得到 myString
# self.sendString(myString)
我还知道 result_of_async_function 是一个非空字符串,因为我将其打印到 stdout 。
我该怎么做才能用异步函数的结果响应客户端?
更新:可运行的源代码
from twisted.internet import reactor, defer, protocol
from twisted.protocols.basic import NetstringReceiver
from twisted.internet.task import deferLater
def f():
return "RESPONSE"
class MyProtocol(NetstringReceiver):
def stringReceived(self, _):
d = deferLater(reactor, 5, f)
d.addCallback(self.reply)
# self.sendString(str(f())) # Note that this DOES send the string.
def reply(self, response):
self.sendString(str(response)) # Why does this not send the string and how to fix?
class MyFactory(protocol.ServerFactory):
protocol = MyProtocol
def main():
factory = MyFactory()
from twisted.internet import reactor
port = reactor.listenTCP(8888, factory, )
print 'Serving on %s' % port.getHost()
reactor.run()
if __name__ == "__main__":
main()
最佳答案
NetstringReceiver
有一项特定功能:
The connection is lost if an illegal message is received
您确定您的消息符合 djb's Netstring protocol ?
显然客户端发送了无法解析的非法字符串,并且由于协议(protocol)条件而导致连接丢失。 代码中的其他内容看起来都不错。
如果你不需要那个特定的协议(protocol),你最好继承LineReceiver
而不是 NetstringReceiver
。
关于Python 扭曲 : A server that writes to the connection after an asynchronous operation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11941382/