PyZMQ套接字在函数中创建时无法发送(PyZMQ socket's fail to send when created in function)

编程入门 行业动态 更新时间:2024-10-27 08:25:47
PyZMQ套接字在函数中创建时无法发送(PyZMQ socket's fail to send when created in function)

使用PyZMQ,当我尝试在函数内创建套接字并使用它发送消息时,永远不会收到消息。

context = zmq.Context() def sender(): sock = context.socket(zmq.PUB) sock.connect("tcp://localhost:44444") sock.send("status good") sender()

但是,如果我在全局范围内创建套接字,它的工作原理如下:

context = zmq.Context() sock = context.socket(zmq.PUB) sock.connect("tcp://localhost:44444") sock.send("status good")

更奇怪的是,检查基础文件描述符上的事件表明事件确实发生了。 但是,使用getsockopt(EVENTS)检查轮询值表示没有任何内容可以从套接字中读取。

我已经尝试在退出之前使函数休眠几秒钟,因此订阅者有足够的时间在套接字被销毁之前读取消息。 但这并没有改变任何事情。

With PyZMQ, when I try to create a socket inside a function and send a message with it, the message is never received.

context = zmq.Context() def sender(): sock = context.socket(zmq.PUB) sock.connect("tcp://localhost:44444") sock.send("status good") sender()

However, if I create the socket in the global scope, it works:

context = zmq.Context() sock = context.socket(zmq.PUB) sock.connect("tcp://localhost:44444") sock.send("status good")

What's even stranger, is that checking for events on the underlying file descriptor shows that an event did occur. However, checking the poll value with getsockopt(EVENTS) indicates that there's nothing to be read from the socket.

I've tried making the function sleep for a few seconds before exiting, so the subscriber has plenty of time to read the message before the socket is destroyed. But this doesn't change anything.

最满意答案

简单解决方案 我忘记了使用ZMQ,您必须在连接之后等待才能发送数据。 一秒睡眠可能就足够了,但在生产代码中使用的方法并不健全。

context = zmq.Context() def sender(): sock = context.socket(zmq.PUB) sock.connect("tcp://localhost:44444") time.sleep(1) sock.send("status good") sender()

在连接完全建立之前发送的任何消息都将被删除。

Simple solution. I forgot that with ZMQ you have to wait after connecting before sending data. A one second sleep is probably sufficient, though not robust method to use in production code.

context = zmq.Context() def sender(): sock = context.socket(zmq.PUB) sock.connect("tcp://localhost:44444") time.sleep(1) sock.send("status good") sender()

Any messages sent before the connection is fully established will just be dropped.

更多推荐

本文发布于:2023-08-07 19:07:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465669.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   socket   PyZMQ   fail   function

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!