PyZMQ: Python bindings for ZeroMQ

27.1.0 · active · verified Sat Mar 28

PyZMQ is the Python binding for ØMQ (ZeroMQ), a high-performance asynchronous messaging library. It enables scalable, distributed messaging without a dedicated message broker, supporting fundamental communication patterns like request-reply, publish-subscribe, and pipeline. The library is actively maintained with frequent releases; the current stable version is 27.1.0, and it supports Python 3.8+.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic Request-Reply pattern using PyZMQ. A server binds to a port, waiting for requests, and sends replies. A client connects to the server, sends requests, and receives replies. The example uses `threading` to run both client and server in the same script for convenience; in a real application, they would typically be separate processes or even on different machines.

import zmq
import time
import threading

def run_server():
    context = zmq.Context()
    socket = context.socket(zmq.REP) # Reply socket
    socket.bind("tcp://*:5555")
    print("Server: Binding to port 5555...")

    try:
        while True:
            message = socket.recv_string()
            print(f"Server: Received request: {message}")
            time.sleep(1) # Simulate some work
            socket.send_string("World")
    except KeyboardInterrupt:
        print("\nServer: Shutting down.")
    finally:
        socket.close()
        context.term()

def run_client():
    context = zmq.Context()
    socket = context.socket(zmq.REQ) # Request socket
    socket.connect("tcp://localhost:5555")
    print("Client: Connecting to server...")

    try:
        for request_num in range(3):
            print(f"Client: Sending Hello {request_num}...")
            socket.send_string(f"Hello {request_num}")
            message = socket.recv_string()
            print(f"Client: Received reply: {message}")
            time.sleep(0.5)
    except KeyboardInterrupt:
        print("\nClient: Shutting down.")
    finally:
        socket.close()
        context.term()

if __name__ == "__main__":
    # Run server in a separate thread for demonstration
    server_thread = threading.Thread(target=run_server)
    server_thread.start()
    time.sleep(0.5) # Give server a moment to bind
    run_client()
    server_thread.join()

view raw JSON →