BillRobertson42
BillRobertson42

Reputation: 12883

Trying to send simple messages with zeromq in python between two hosts

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

Answers (3)

user650654
user650654

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

Zangetsu
Zangetsu

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

BillRobertson42
BillRobertson42

Reputation: 12883

It looks like I need to make one socket a PULL socket and the other a PUSH socket.

Upvotes: 0

Related Questions