Ruby和Python之间的ZeroMQ对/对连接

2024-05-15 13:31:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用ZeroMQ在Python程序和Ruby程序之间建立一个简单的连接,我正在尝试使用PAIR连接,但我一直无法实现

这是我用python(服务器)编写的代码:

import zmq 
import time 

port = "5553" 
context = zmq.Context() 
socket = context.socket(zmq.PAIR) 
socket.bind("tcp://*:%s" % port) 

while True: 
    socket.send(b"Server message to client3") 
    print("Enviado mensaje") 
    time.sleep(1)

在连接客户端之前,它不会显示任何内容

这是Ruby(客户端)中的代码

require 'ffi-rzmq'
context = ZMQ::Context.new
subscriber = context.socket ZMQ::PAIR
subscriber.connect "tcp://localhost:5553"
loop do
    address = ''
    subscriber.recv_string address
    puts "[#{address}]"
end

ruby脚本只是冻结,不打印任何内容,python脚本开始打印Enviando mensaje

B.T.W:我正在使用Python 3.6.9和Ruby 2.6.5

在Ruby和Python之间连接zmqPAIR的正确方法是什么


Tags: 代码import程序timeportaddresscontextsocket
1条回答
网友
1楼 · 发布于 2024-05-15 13:31:17

欢迎来到零之禅
如果您从未使用过ZeroMQ,
在这里,人们可能喜欢先看一下“ZeroMQ Principles in less than Five Seconds”,然后再深入了解更多细节

Q : It does not display anything until I connect a client.

当然,它不会,您的代码会被强制要求阻止,直到PAIR/PAIR传递通道能够传递消息为止。正如v4.2+API定义的那样,.send()-方法将在“静音状态的所有持续时间内阻塞

When a ZMQ_PAIR socket enters the mute state due to having reached the high water mark for the connected peer, or if no peer is connected, then any zmq_send(3) operations on the socket shall block until the peer becomes available for sending; messages are not discarded.

可以尝试非阻塞发送模式(这始终是避免阻塞的良好工程实践的标志,在中越多),最好将<aSocket>.close()<aContext>.term()作为经验法则(最好使用显式.setsockopt( zmq.LINGER, 0 ))为了避免挂起,作为一种良好的工程实践,明确关闭资源并将其释放回系统

socket.send( b"Server message #[_{0:_>10d}_] to client3".format( i ), zmq.NOBLOCK )

最后但并非最不重要的是:

Q : What is the correct way to connect a zmq PAIR between Ruby and Python?

正如API文档所解释的:

ZMQ_PAIR sockets are designed for inter-thread communication across the zmq_inproc(7) transport and do not implement functionality such as auto-reconnection.

没有最好的方法可以做到这一点,因为Python/Ruby不是线程间通信的例子。自v2.1+以来,ZeroMQ明确警告,PAIR/PAIR原型是一种实验性,使用时应牢记这一点

人们总是可以用一系列的PUSH/PULL-单工信道来替代每个这样的用例,用一对仅.send()的+.recv()信道提供相同的舒适性

相关问题 更多 >