ZeroMQ sockets is another great python networking module which you can use for the communication between client and server program. In this article we will write a client side program and a server side program and make them communicate with each other with the help of ZeroMQ sockets. First of all, ZeroMQ socket module does not come with the Python3 package so you will need to install it through the command line as usual.
pip install pyzmq
Once you have done that let start to create the client server with below code.
import zmq host = '127.0.0.1' port = 6999 context = zmq.Context() server = context.socket(zmq.REP) server.bind("tcp://%s:%s" % (host, port)) # Let the server runs forever while True: request_bytes = server.recv() request_str = request_bytes.decode('utf-8') reply_str = "Nice to meet you %s" % request_str reply_bytes = bytes(reply_str, 'utf-8') server.send(reply_bytes)
Don’t use ‘localhost’ for the host name, you need to provide the ip address instead.
Start the above program.
Next create the client program.
import zmq host = '127.0.0.1' port = 6999 context = zmq.Context() client = context.socket(zmq.REQ) client.connect("tcp://%s:%s" % (host, port)) print("Hi my name is James") request_str = "JAMES" request_bytes = request_str.encode('utf-8') client.send(request_bytes) reply_bytes = client.recv() reply_str = reply_bytes.decode('utf-8') print("Server said : %s" % (reply_str))
Start the client program.
Basically the server program will receive a name from the client program and then sends the message back to the client, ZeroMQ can communicate with many clients one after another which is what the word Q means.