让twister服务器占据主动
我有一个扭曲的服务器,实现了 LineReceiver 协议。 当我调用 sendLine
来响应客户端消息时,它会立即将该行写入客户端,正如人们所期望的那样。
但是假设客户端要求服务器进行冗长的计算。我希望服务器定期向客户端发送进度消息。当服务器主动调用 sendLine
而客户端没有请求任何内容时,它似乎会等待客户端向服务器发送消息,然后再发送任何内容。
如何立即从服务器向客户端发送消息,而不需要客户端明确请求?
I have a server in twisted, implementing a LineReceiver
protocol.
When I call sendLine
in response to a client message, it writes the line to the client immediately, as one would expect.
But say the client asks the server to do a lengthy calculation. I want the server to periodically send a progress message to the client. When the server takes initiative and calls sendLine
without the client having asked for anything, it seems to wait for the client to send a message to the server before sending anything.
How do I send a message from the server to the client immediately, without having the client explicitly ask for it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果“立即”是指“当客户端连接时”,请尝试在
LineReceiver
子类的connectionMade
中调用sendLine
。If by "immediately" you mean "when the client connects", try calling
sendLine
in yourLineReceiver
subclass'sconnectionMade
.如果异步执行计算,请使用延迟。
另一种方式,如果它是在单独的线程中进行一些长计算,由 deferrToThread() 开始,请使用reactor.callFromThread()
(我假设我们不在主循环中进行大量计算 - 这是非常非常错误的:))
小例子:
因此现在我们将通知客户端处理每 10 块数据,然后最终向他发送结果。
代码可能有点不正确,它只是例如
docs
UPD:
只是为了澄清:
错过了 sendLine 部分。一般来说没关系,调用它而不是transport.write()
Use deferreds if you perform calculation asynchronously.
Other way if it's some long calculation in separate Thread, started by lets say deferrToThread(), use reactor.callFromThread()
(I assume we don't do heavy calculation in main loop - that's very, very wrong :))
little example:
Thus now we'll notify client about processing every 10 chunks of data, and then finally send him result.
code may be little incorrect, it's just e.g.
docs
UPD:
just for clarification:
missed sendLine part. Generally it doesn't matter, call it insted of transport.write()
您可以随时使用
sendLine
发送一行,它应该立即到达,但您可能会遇到与服务器阻塞相关的问题。对
sendLine
的调用会被延迟,因此,如果您在一堆处理过程中进行调用,则可能会在一段时间内没有执行操作,然后在收到消息时 ,反应器中断处理,接收消息,并在返回处理之前获取发送的排队消息。您应该阅读此处的一些其他答案,并确保您的处理不会阻塞您的主线程。You can send a line using
sendLine
whenever you want and it should arrive immediately, but you may have a problem related to your server blocking.A call to
sendLine
is deferred, so if you make a call in the middle of a bunch of processing, it's possible that it's not being actioned for a while, and then when a message is received, the reactor interrupts the processing, receives the message, and gets the queued message sent before going back to processing. You should read some of the other answers here and make sure that your processing isn't blocking up your main thread.