如何使用Zeromq的inproc和ipc传输?

18 投票
4 回答
42948 浏览
提问于 2025-04-17 08:18

我刚接触ZERMQ。ZeroMQ有几种传输方式,包括TCP、INPROC和IPC。我在找一些用Python和inproc的例子,最好是在Winx64和Python 2.7下的,这些例子也能在Linux上用。

另外,我一直在寻找UDP的传输方法,但找不到相关的例子。

我找到的唯一一个例子是:

import zmq
import zhelpers

context = zmq.Context()

sink = context.socket(zmq.ROUTER)
sink.bind("inproc://example")

# First allow 0MQ to set the identity
anonymous = context.socket(zmq.XREQ)
anonymous.connect("inproc://example")
anonymous.send("XREP uses a generated UUID")
zhelpers.dump(sink)

# Then set the identity ourself
identified = context.socket(zmq.XREQ)
identified.setsockopt(zmq.IDENTITY, "Hello")
identified.connect("inproc://example")
identified.send("XREP socket uses REQ's socket identity")
zhelpers.dump(sink)

我想到的使用场景是:像UDP那样分发信息。测试使用TCP的Push/Pull会更快,还是inproc会更快呢?

这是测试例子>..............

服务器:

import zmq
import time

context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("inproc://example2")

while True:
    #  Wait for next request from client
    message = socket.recv()
    print "Received request: ", message

    #  Do some 'work'
    time.sleep (1)        #   Do some 'work'

    #  Send reply back to client
    socket.send("World")

客户端:

import zmq

context = zmq.Context()

#  Socket to talk to server
print "Connecting to hello world server..."
socket = context.socket(zmq.REQ)
socket.connect ("inproc://example2")

#  Do 10 requests, waiting each time for a response
for request in range (1,10):
    print "Sending request ", request,"..."
    socket.send ("Hello")

    #  Get the reply.
    message = socket.recv()
    print "Received reply ", request, "[", message, "]"

错误信息:

 socket.connect ("inproc://example2")
File "socket.pyx", line 547, in zmq.core.socket.Socket.connect (zmq\core\socket.c:5347)
zmq.core.error.ZMQError: Connection refused

4 个回答

5

从2016年3月开始,ZeroMQ支持线程安全的UDP:

  • 你需要使用广播/接收模式(这和发布/订阅模式很相似)
  • 这个功能在libzmq和czmq中都可以使用
  • 可以查看libzmq源代码中的 tests/test_udp.cpptests/test_radio_dish.cpp
  • Doron Somech在zeromq-dev@邮件列表中详细解释了这个功能,具体可以看这里:线程安全的发布/订阅和多播
10

如果你使用的是 ZMQ_PUB 或 ZMQ_SUB 这两种套接字(不过在你给的例子中并没有用到这两种,而是用到了 ROUTER、XREQ 等),那么你可以使用 UDP,准确来说,是通过UDP 多播来实现。

"epgm://host:port"

EPGM 是指 封装的 PGM,也就是把 PGM 封装在 UDP 里,这样比直接使用 PGM 更容易和现有的网络基础设施兼容。

你也可以查看 http://api.zeromq.org/2-1:zmq-pgm 了解更多信息。

不过,我不知道有没有支持单播场景的 UDP。

14

根据我所了解,0MQ不支持UDP协议。而且,IPC(进程间通信)只在那些符合POSIX标准的操作系统上支持命名管道;所以在Windows系统上,你实际上只能使用'inproc'、TCP或者PGM。不过,除了这些限制之外,0MQ的一个主要特点是你的协议只是地址的一部分。你可以拿任何例子,改变一下套接字地址,其他的内容应该都能正常工作(当然,这要遵循之前提到的限制)。另外,ZGuide上有很多示例(其中不少是用Python写的)。

撰写回答