KSp
KSp

Reputation: 1239

Subscriber does not receive message, Pyzmq

I am trying to publish a message(it's like broadcast when using raw sockets) to my subnet with a known port but at subscriber end, the message is not received. The idea is the IP address of the first machine should not be known to the second machine that's why I am using broadcast IP. With UDP or TCP raw socket, it works but I am trying to learn pub-sub pattern not sure how to incorporate that idea.


This is my codes:

Publisher:

import zmq
import sys
import time
context=zmq.Context()
socket=context.socket(zmq.PUB)
socket.bind("tcp://192.168.1.255:5677")
while True:
    data='hello'.encode()
    socket.send(data)
    #time.sleep(1)

Subscriber:

context=zmq.Context()
    sub=context.socket(zmq.PUB)
    sub.setsocketopt(zmq.SUBSCRIBE, "".encode())
    sub.connect('tcp://192.168.1.255:5677')
    sub.recv()
    print(sub.recv())

In terms of raw UDP, I wrote a code which works perfectly.

broadcast:

def broadcast(Host,port):
    #send bd
    sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    msg=get_ip_data("wlp3s0")
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    time.sleep(1.5)
    # print("yes sending", client)

    sock.sendto(msg.encode(), (Host,port))

recv:

def broadcast_recv():
    #listen bd
    sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    sock.bind((get_bd_address("wlp1s0"),12345))
    # receive broadcast
    msg, client = sock.recvfrom(1024)
    a=(msg.decode())
    print(a)

Upvotes: 0

Views: 2134

Answers (2)

Benyamin Jafari
Benyamin Jafari

Reputation: 34006

It seems you forgot the zmq.SUB in the subscriber side. Also you used sub.setsocketopt() instead of sub.setsockopt().


Try it:

Publisher:

import zmq
import time

context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.bind("tcp://*:5677")  # Note.

while True:
    socket.send_string('hello')
    time.sleep(1)

Subscriber:

context = zmq.Context()
sub=context.socket(zmq.SUB)  # Note.
sub.setsockopt(zmq.SUBSCRIBE, b"")  # Note.
sub.connect('tcp://192.168.1.255:5677')

while True:
    print(sub.recv())

[NOTE]:

  • You can also change the .bind() and .connect() in subscriber and publisher with your policy. (This post is relevant).
  • Make sure that 5677 is open in the firewall.
  • socket.bind("tcp://*:5677") or socket.bind("tcp://0.0.0.0:5677") is broadcasting trick.

Upvotes: 3

user3097732
user3097732

Reputation: 159

I think the problem is that the SUB socket cannot register itself with the PUB socket. Even though in-concept the data only goes from PUB to SUB, in reality, there are also control messages (e.g. subscription topics), being sent back to the PUB.

If your netmask is 255.255.255.0, this will probably not work as expected.

Upvotes: 0

Related Questions