尝试在两个主机之间使用python中的zeromq发送简单消息

时间:2013-05-14 18:40:42

标签: python zeromq

在机器1上运行的脚本

import zmq

context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.bind("tcp://127.0.0.1:5000")
print "socket bound"

while True:
    print "Waiting for message"
    message = socket.recv()
    print "message received: " + str(message)

此脚本进入socket.recv(),然后永远不会从该调用返回。

发送数据的过程在machine2上运行

import zmq

context = zmq.Context()
socket = context.socket(zmq.PUB)
print "socket created"
socket.connect("tcp://machine2:5000")
print "socket connected"

for i in range(1, 3):
    print "About to send " + str(i)
    socket.send("Hello " + str(i))
    print "Sent " + str(i)

print "About to close socket"
socket.close()

print "Socket closed"

执行完成,但永远不会结束......

$ python bar.py
socket created
socket connected
About to send 1
Sent 1
About to send 2
Sent 2
About to close socket
Socket closed

我显然做错了,如何创建一个'队列'来接收远程主机上发布的多条消息?

3 个答案:

答案 0 :(得分:3)

只需要正确绑定套接字并使用setsockopt设置选项,如下所示。会没事的。

import zmq
import socket



context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.setsockopt(zmq.SUBSCRIBE, "")

socket.bind("tcp://*:5000")
print "socket bound"

while True:
    print "Waiting for message"
    message = socket.recv()
    print "message received: " + str(message)

答案 1 :(得分:2)

以下是PUB绑定和SUB连接的工作示例 - 首先启动发布者,然后启动订阅者:

pub.py

import time
import zmq

context = zmq.Context()
socket = context.socket(zmq.PUB)
print "socket created"
socket.bind('tcp://*:5000')
print "socket connected"

channel = '1001'
i = 0
while True:
    message = 'Hello %s' % i
    socket.send("%s %s" % (channel, message))
    print "Published: %s " % message
    time.sleep(0.5)
    i += 1

print "About to close socket"
socket.close()
print "Socket closed"

sub.py(用适当的主机名/ IP替换发布者):

import zmq

context = zmq.Context()
channel = '1001'
socket = context.socket(zmq.SUB)
socket.setsockopt(zmq.SUBSCRIBE, 'channel')
socket.connect('tcp://publisher:5000')
print "socket connected"

while True:
    print "Waiting for message"
    message = socket.recv()
    print "message received: ", message

答案 2 :(得分:0)

看起来我需要将一个套接字设为PULL套接字而另一个设置为PUSH套接字。