[英]Publishing messages from Twisted Client to ZeroMQ
In my Twisted application , i want to publish messages to the ZeroMQ message queue. 在我的Twisted应用程序中,我想将消息发布到ZeroMQ消息队列中。 Can i do something like below in the Protocol class ?
我可以在Protocol类中做以下类似的事情吗?
from twisted.internet import protocol,reactor
import zmq
class MyClient(protocol.Protocol):
def __init__(self):
self.context = zmq.Context()
self.socket = context.socket(zmq.PUB)
self.socket.bind("tcp://127.0.0.1:5000")
def dataReceived(self,data):
#Do something with the data to get a result
#...
#Publish to 0mq
self.socket.send(result)
#Code below for factory and initializing reactor
#...
reactor.run()
Would the above work, if not why ?. 上面的工作是否可行? If it wont work then should I use txZMQ ( https://github.com/smira/txZMQ ) ?
如果它不起作用,那我应该使用txZMQ( https://github.com/smira/txZMQ )吗?
Thanks 谢谢
The default behaviour of the Socket.send
method is to block until the message has been queued on the socket. Socket.send
方法的默认行为是阻塞,直到消息在套接字上排队为止。 If the socket queue is full, then nothing else will happen in your Twisted application until there is room on the socket to queue the message. 如果套接字队列已满,则在套接字上没有空间将消息排队之前,Twisted应用程序中不会发生其他任何事情。
The NOBLOCK
flag to the send
method tells zmq
to raise an exception if it can't queue the message. send
方法的NOBLOCK
标志告诉zmq
如果无法将消息排队,则引发异常。 But if you do this, then you have to worry about failures: 但是,如果执行此操作,则必须担心失败:
try:
self.socket.send(result, flags=zmq.NOBLOCK)
except zmq.Again:
# Failed to queue the message: what now?
It would simpler to use the txZMQ package, which integrates ZMQ with the Twisted event loop. 使用txZMQ软件包会更简单,该软件包将ZMQ与Twisted事件循环集成在一起。 The examples in the documentation suggest that you implement publishing in txZMQ like this:
文档中的示例建议您在txZMQ中实施发布,如下所示:
factory = ZmqFactory()
publisher = ZmqPubConnection(factory, endpoint)
publisher.publish(message)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.