Reputation: 12883
Script running on machine 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)
This script gets to the socket.recv() and then never returns from that call.
The process that sends the data runs on 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"
Executes to completion, but never finishes...
$ 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
I'm obviously doing it wrong, how do I create a 'queue' to receive multiple messages from publishes on remote hosts?
Upvotes: 2
Views: 8805
Reputation: 6148
Here is a working example with PUB binding and SUB connecting - start the publisher first and then the subscriber:
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 (replace publisher with appropriate hostname/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
Upvotes: 3
Reputation: 2015
Just need to bind the socket properly and set option using setsockopt as given below. It will be fine..
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)
Upvotes: 3
Reputation: 12883
It looks like I need to make one socket a PULL socket and the other a PUSH socket.
Upvotes: 0