Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ZMQ responder not receiving message

I am trying a simple zmq script but somehow the responder is not getting the first message.

The Responder looks like this:

def main():
    context = zmq.Context()
    socket = context.socket(zmq.REP)
    socket.connect("tcp://localhost:{}".format(5560))
    print("connected ...")
    while True:
          #  Wait for next request from client
          message = socket.recv_pyobj()
          #print (message)
          print(message)
if __name__ == '__main__':
    main()

I am sending the request with the following code from another process:

def main():
    context = zmq.Context()
    socket = context.socket(zmq.REQ)
    socket.connect("tcp://localhost:{}".format(5560))
    print("sending object")
    socket.send_pyobj("ok")
    print("done")

if __name__ == '__main__':
    main()

Does anybody have an idea why it does not arrive?

like image 853
GöCo Avatar asked Nov 16 '22 03:11

GöCo


1 Answers

You must add .bind() an IP address in your REP code snippet instead of .connect(). In REP/REQ pattern there are the request and response factor, so you can throw feedback in the responder code. Thus your code will be as follows:

Responder:

import zmq

def main():
    context = zmq.Context()
    socket = context.socket(zmq.REP)
    socket.bind("tcp://127.0.0.1:5560")
    while True:
        message = socket.recv_pyobj()
        print(message)
        socket.send_string('Your message received.')

if __name__ == '__main__':
    main()

Request code snippet:

import zmq

def main():
    context = zmq.Context()
    socket = context.socket(zmq.REQ)
    socket.connect("tcp://localhost:5560")
    print("sending object")
    socket.send_pyobj("ok")
    message = socket.recv()
    print(message)

if __name__ == '__main__':
    main()

Out (req):

sending object
b'Your message received.'

Out (rep):

ok

[NOTE]:

  • If you want to send a simple string without any response, using the PUSH/PULL or SUB/PUB pattern is more suitable instead of using REP/REQ and also you could use the socket.send_string('ok') instead of socket.send_pyobj('ok') in request section and socket.recv() instead of socket.recv_pyobj() in responder.

  • Note that in .bind() case, you shouldn't use the localhost string Relevant Post.

like image 98
Benyamin Jafari Avatar answered Dec 06 '22 22:12

Benyamin Jafari