Pynng

0.9.0 · active · verified Fri Apr 17

Pynng is a Python binding for the nng (nanomsg-next-generation) C library, providing lightweight, high-performance messaging patterns for network communication. It supports both synchronous and asynchronous (asyncio) operations, making it suitable for a wide range of network applications. The current version is 0.9.0, and it generally follows a moderate release cadence, with updates often introducing significant features or improvements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic asynchronous request-reply (REQ/REP) pattern using pynng. It sets up a minimal server that listens for messages and replies, and a client that sends messages and receives replies. Both are run concurrently using asyncio.

import pynng
import asyncio

async def main():
    addr = "tcp://127.0.0.1:5555"

    async def server():
        """Simple Request-Reply server."""
        with pynng.Rep0() as rep_sock:
            rep_sock.listen(addr)
            print("Server: Listening...")
            # Receive and immediately reply, then close after 2 messages
            for _ in range(2):
                msg = await rep_sock.arecv()
                print(f"Server: Received '{msg.decode()}'")
                await rep_sock.asend(b"PONG")
            print("Server: Done.")

    async def client():
        """Simple Request-Reply client."""
        await asyncio.sleep(0.1) # Give server a moment to start
        with pynng.Req0() as req_sock:
            req_sock.dial(addr)
            print("Client: Dialed.")
            for i in range(2):
                await req_sock.asend(f"PING {i}".encode())
                reply = await req_sock.arecv()
                print(f"Client: Received '{reply.decode()}'")
            print("Client: Done.")

    await asyncio.gather(server(), client())

if __name__ == "__main__":
    # This example demonstrates async usage, which is common in modern pynng applications.
    asyncio.run(main())

view raw JSON →