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?
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:
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()
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()
sending object
b'Your message received.'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With