Create networking with ZeroMQ sockets

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 = ''
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')

Don’t use ‘localhost’ for the host name, you need to provide the ip address instead.

Start the above program.

server program
server program

Next create the client program.

import zmq
host = ''
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')
reply_bytes = client.recv()
reply_str = reply_bytes.decode('utf-8')
print("Server said : %s" % (reply_str))

Start the client program.

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.

Leave a Reply

Be the First to Comment!

Notify of