Python 扭曲 : A server that writes to the connection after an asynchronous operation?

标签 python networking asynchronous twisted deferred

我有一个服务器,我在其中实现了 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/

相关文章:

python - 重复和选择函数的轻微变化的快速 Numpy 计算

c - 关于htonl的源码

linux - 模拟网络与真实主机之间的桥梁

javascript - 等待 Node.js Express 应用程序在 for 循环中调用 http.request

node.js - 如何在readline中定义异步函数

Javascript 使用 Promises 为 For 循环的每个项目运行异步代码

python - for循环python多次检查

python - 如何在 OpenCV Python Stitcher 类中设置全景模式?

android - webview 错误屏幕显示空白页

python - Numpy 确实对待 float ('nan' ) 并且 float 不同 - 转换为 None