### Basic Request/Response Setup Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/configuration.md Example of setting up a basic request/response communication pattern with custom timeouts and reconnection settings. ```python import pynng # Server with timeouts rep = pynng.Rep0( listen='tcp://127.0.0.1:5555', recv_timeout=5000, # 5 second receive timeout send_timeout=5000, # 5 second send timeout name='request-handler' ) # Client with shorter timeouts req = pynng.Req0( dial='tcp://127.0.0.1:5555', recv_timeout=2000, send_timeout=2000, reconnect_time_min=100, reconnect_time_max=5000, name='client' ) ``` -------------------------------- ### Install pynng Source: https://github.com/codypiersall/pynng/blob/master/docs/index.md Instructions for installing pynng using pip. ```bash pip3 install pynng ``` -------------------------------- ### Install Python Package Source: https://github.com/codypiersall/pynng/blob/master/CMakeLists.txt Installs the Python 'pynng' package directory. ```cmake install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/pynng/ DESTINATION ${SKBUILD_PROJECT_NAME} FILES_MATCHING PATTERN "*.py" PATTERN "__pycache__" EXCLUDE) ``` -------------------------------- ### listen Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-socket.md Example of listening on a local address. ```python s = pynng.Pair0() listener = s.listen('tcp://127.0.0.1:5555') ``` -------------------------------- ### Pub/Sub Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-socket.md A complete example demonstrating the publish/subscribe pattern with Pub0 and Sub0 sockets. ```python import pynng pub = pynng.Pub0(listen='tcp://127.0.0.1:5555') sub = pynng.Sub0( dial='tcp://127.0.0.1:5555', topics=[b'sports', b'news'] ) pub.send(b'sports:goal') # Received by sub pub.send(b'news:headline') # Received by sub pub.send(b'weather:sunny') # NOT received by sub msg = sub.recv() print(msg) # b'sports:goal' ``` -------------------------------- ### Context Options Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-context-tls.md Example of setting receive and send timeouts for a context. ```python ctx = req.new_context() ctx.recv_timeout = 5000 # 5 second timeout ctx.send_timeout = 5000 ``` -------------------------------- ### Basic CMake Setup Source: https://github.com/codypiersall/pynng/blob/master/CMakeLists.txt Initializes CMake version and project name. ```cmake cmake_minimum_required(VERSION 3.26) project(${SKBUILD_PROJECT_NAME} LANGUAGES C) ``` -------------------------------- ### Pair1 Protocol Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/index.md Example of setting up a Pair1 socket for polyamorous communication. ```python s = Pair1(polyamorous=True, listen='tcp://127.0.0.1:5555') ``` -------------------------------- ### Listener Options Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-connections.md Example of setting listener options and accessing properties. ```python listener = s.listen('tcp://127.0.0.1:5555') listener.tcp_nodelay = True print(listener.url) # 'tcp://127.0.0.1:5555' ``` -------------------------------- ### Dialer Options Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-connections.md Example of setting dialer options and accessing properties. ```python dialer = s.dial('tcp://127.0.0.1:5555') dialer.tcp_nodelay = True print(dialer.url) # 'tcp://127.0.0.1:5555' ``` -------------------------------- ### Listener Constructor Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-connections.md Example of creating a listener using Socket.listen(). ```python listener = socket.listen('tcp://127.0.0.1:5555') ``` -------------------------------- ### Pipe callbacks example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-connections.md Example of setting up callbacks for pipe connection and disconnection events. ```python import pynng def on_pipe_connect(pipe): print(f"Pipe {pipe.id} connected from {pipe.remote_address}") def on_pipe_disconnect(pipe): print(f"Pipe {pipe.id} disconnected") socket = pynng.Pair0(listen='tcp://127.0.0.1:5555') socket.add_post_pipe_connect_cb(on_pipe_connect) socket.add_post_pipe_remove_cb(on_pipe_disconnect) # Use socket, callbacks will be invoked ``` -------------------------------- ### Pipe options example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-connections.md Example of monitoring all pipes connected to a socket and printing their details. ```python # Monitor all pipes for pipe in socket.pipes: print(f"Pipe {pipe.id}: {pipe.url}") print(f" Local: {pipe.local_address}") print(f" Remote: {pipe.remote_address}") print(f" Protocol: {pipe.protocol_name}") ``` -------------------------------- ### Publish/Subscribe with Buffers Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/configuration.md Example demonstrating Publish/Subscribe pattern with buffer size configurations. ```python import pynng ``` -------------------------------- ### Library Constants Examples Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/types.md Examples of accessing NNG library constants. ```python import pynng # Socket address families pynng.lib.NNG_AF_UNSPEC pynng.lib.NNG_AF_INPROC pynng.lib.NNG_AF_IPC pynng.lib.NNG_AF_INET pynng.lib.NNG_AF_INET6 pynng.lib.NNG_AF_ZT pynng.lib.NNG_AF_ABSTRACT # TLS modes pynng.lib.NNG_TLS_MODE_CLIENT pynng.lib.NNG_TLS_MODE_SERVER # TLS auth modes pynng.lib.NNG_TLS_AUTH_MODE_NONE pynng.lib.NNG_TLS_AUTH_MODE_OPTIONAL pynng.lib.NNG_TLS_AUTH_MODE_REQUIRED # Pipe events pynng.lib.NNG_PIPE_EV_ADD_PRE pynng.lib.NNG_PIPE_EV_ADD_POST pynng.lib.NNG_PIPE_EV_REM_POST # Flags pynng.lib.NNG_FLAG_ALLOC pynng.lib.NNG_FLAG_NONBLOCK ``` -------------------------------- ### Trio Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/index.md Basic example of using pynng with Trio for asynchronous message reception. ```python import pynng import trio async def main(): s = pynng.Pair0(dial='tcp://localhost:5555') msg = await s.arecv() print(msg) trio.run(main) ``` -------------------------------- ### Executable Python code examples Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/README.md Demonstrates how to create a Pair0 socket. ```python # Executable Python code examples socket = pynng.Pair0() ``` -------------------------------- ### Dialer Constructor Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-connections.md Example of creating a dialer using Socket.dial(). ```python dialer = socket.dial('tcp://127.0.0.1:5555') ``` -------------------------------- ### send example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-connections.md Example of sending a response to a specific peer in a Pair1 polyamorous socket. ```python # In a Pair1 polyamorous socket, send to a specific peer msg = socket.recv_msg() msg.pipe.send(b'response to this peer only') ``` -------------------------------- ### Server with certificate Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-context-tls.md Example of configuring a TLS server with a certificate and using it with a socket. ```python import pynng # Configure TLS server tls = pynng.TLSConfig( pynng.TLSConfig.MODE_SERVER, cert_key_file='/path/to/cert.pem' ) # Use with socket server = pynng.Pair0( listen='tls+tcp://127.0.0.1:8883', tls_config=tls ) ``` -------------------------------- ### Curio Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/index.md Basic example of using pynng with Curio for asynchronous message reception. ```python import pynng import curio async def main(): s = pynng.Pair0(dial='tcp://localhost:5555') msg = await s.arecv() print(msg) curio.run(main) ``` -------------------------------- ### Basic Usage Source: https://github.com/codypiersall/pynng/blob/master/README.md A simple example demonstrating how to use pynng sockets for communication. ```python from pynng import Pair0 s1 = Pair0() s1.listen('tcp://127.0.0.1:54321') s2 = Pair0() s2.dial('tcp://127.0.0.1:54321') s1.send(b'Well hello there') print(s2.recv()) s1.close() s2.close() ``` -------------------------------- ### Setting TLS options on Listener/Dialer Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-context-tls.md Example showing how to set TLS options directly on Listener and Dialer objects. ```python import pynng socket = pynng.Pair0() # Listen with TLS configuration from files listener = socket.listen('tls+tcp://127.0.0.1:8883') listener.tls_cert_key_file = '/path/to/cert.pem' listener.tls_ca_file = '/path/to/ca.pem' listener.tls_auth_mode = pynng.TLSConfig.AUTH_MODE_OPTIONAL # Dial with TLS configuration from files dialer = socket.dial('tls+tcp://example.com:8883') dialer.tls_ca_file = '/path/to/ca.pem' dialer.tls_server_name = 'example.com' ``` -------------------------------- ### Socket Usage Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-socket.md Example demonstrating the creation and basic usage of Pair0 sockets, including context manager and custom option settings. ```python from pynng import Pair0 # Simple creation with context manager with Pair0(listen='tcp://127.0.0.1:5555') as s1, \ Pair0(dial='tcp://127.0.0.1:5555') as s2: s1.send(b'hello') msg = s2.recv() # With custom options s = Pair0( recv_timeout=1000, send_timeout=1000, name='my-socket' ) s.listen('tcp://127.0.0.1:5555') ``` -------------------------------- ### Asyncio Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/index.md Basic example of using pynng with asyncio for asynchronous message reception. ```python import pynng import asyncio async def main(): s = pynng.Pair0(dial='tcp://localhost:5555') msg = await s.arecv() print(msg) asyncio.run(main()) ``` -------------------------------- ### InprocAddr Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/types.md Example demonstrating the use of InprocAddr for in-process communication. ```python s1 = pynng.Pair0(listen='inproc://service') s2 = pynng.Pair0(dial='inproc://service') addr = s1.local_address # InprocAddr print(f"Address: {addr.name}") # 'service' ``` -------------------------------- ### Install Python Extension Module Source: https://github.com/codypiersall/pynng/blob/master/CMakeLists.txt Installs the compiled '_nng' Python extension module. ```cmake install(TARGETS _nng DESTINATION ${SKBUILD_PROJECT_NAME}) ``` -------------------------------- ### new_context Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-socket.md Example of creating new contexts for concurrent operations. ```python s = pynng.Req0() ctx1 = s.new_context() ctx2 = s.new_context() # Can now make concurrent requests with different contexts ``` -------------------------------- ### Mutual TLS authentication Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-context-tls.md Example demonstrating mutual TLS authentication for both server and client configurations. ```python import pynng # Server configuration server_tls = pynng.TLSConfig( pynng.TLSConfig.MODE_SERVER, cert_key_file='/path/to/server-cert.pem', ca_files='/path/to/client-ca.pem', auth_mode=pynng.TLSConfig.AUTH_MODE_REQUIRED ) # Client configuration client_tls = pynng.TLSConfig( pynng.TLSConfig.MODE_CLIENT, server_name='server.example.com', cert_key_file='/path/to/client-cert.pem', ca_files='/path/to/server-ca.pem' ) # Use both server = pynng.Pair0( listen='tls+tcp://127.0.0.1:8883', tls_config=server_tls ) client = pynng.Pair0( dial='tls+tcp://server.example.com:8883', tls_config=client_tls ) ``` -------------------------------- ### In6Addr Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/types.md Example demonstrating the use of In6Addr for IPv6 socket addresses. ```python s = pynng.Pair0(listen='tcp://[::1]:5555') addr = s.local_address # In6Addr print(str(addr)) # '[::1]:5555' ``` -------------------------------- ### Transport Types Examples Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/types.md Examples of listening on different transport protocols. ```python s = pynng.Pair0() s.listen('tcp://127.0.0.1:5555') # IPv4 TCP s.listen('tcp://[::1]:5555') # IPv6 TCP s.listen('ipc:///tmp/nng.sock') # Unix domain socket s.listen('inproc://service') # In-process s.listen('tls+tcp://host:port') # TLS secured ``` -------------------------------- ### Pull0 Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-socket.md A basic example of setting up a Pull0 socket to listen for incoming messages. ```python puller = pynng.Pull0(listen='tcp://127.0.0.1:5555') msg = puller.recv() print(msg) ``` -------------------------------- ### Client with CA verification Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-context-tls.md Example of configuring a TLS client with CA verification and using it with a socket. ```python import pynng # Configure TLS client tls = pynng.TLSConfig( pynng.TLSConfig.MODE_CLIENT, server_name='example.com', ca_files='/path/to/ca.pem' ) # Use with socket client = pynng.Pair0( dial='tls+tcp://example.com:8883', tls_config=tls ) ``` -------------------------------- ### IPCAddr Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/types.md Example demonstrating the use of IPCAddr for inter-process communication. ```python s1 = pynng.Pair0(listen='ipc:///tmp/nng.sock') s2 = pynng.Pair0(dial='ipc:///tmp/nng.sock') addr = s1.local_address # IPCAddr print(f"Path: {addr.path}") # '/tmp/nng.sock' ``` -------------------------------- ### Pipe Callbacks Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/index.md Illustrates registering callbacks for connection lifecycle events. ```python socket.add_post_pipe_connect_cb(on_connect) socket.add_post_pipe_remove_cb(on_disconnect) ``` -------------------------------- ### Pair0 Protocol Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/index.md Example of bidirectional communication with exactly one peer using Pair0. ```python s1 = Pair0(listen='tcp://127.0.0.1:5555') s2 = Pair0(dial='tcp://127.0.0.1:5555') s1.send(b'msg') s2.recv() # b'msg' ``` -------------------------------- ### Async Usage with Trio Source: https://github.com/codypiersall/pynng/blob/master/README.md An example demonstrating asynchronous communication using pynng with the Trio framework. ```python import pynng import trio async def send_and_recv(sender, receiver, message): await sender.asend(message) return await receiver.arecv() with pynng.Pair0(listen='tcp://127.0.0.1:54321') as s1, \ pynng.Pair0(dial='tcp://127.0.0.1:54321') as s2: received = trio.run(send_and_recv, s1, s2, b'hello there old pal!') assert received == b'hello there old pal!' ``` -------------------------------- ### AbstractAddr Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/types.md Example demonstrating the use of AbstractAddr for abstract socket addresses on Linux. ```python s = pynng.Pair0(listen='abstract://myservice') addr = s.local_address # AbstractAddr print(f"Name: {addr.name}") # 'myservice' ``` -------------------------------- ### Pair1 Polyamorous Option Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/types.md Example showing how to check the polyamorous mode of a Pair1 socket. ```python s = pynng.Pair1(polyamorous=True) assert s.polyamorous == True ``` -------------------------------- ### Socket Option Descriptors Examples Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/types.md Examples of using various socket option descriptor types. ```python Example: socket.protocol, socket.ttl_max ``` ```python Example: socket.recv_timeout, socket.reconnect_time_min ``` ```python Example: socket.recv_max_size ``` ```python Example: socket.name, socket.protocol_name ``` ```python Example: socket.raw, socket.tcp_nodelay ``` ```python Example: socket.local_address, pipe.remote_address ``` ```python Example: socket.tls_config ``` -------------------------------- ### Message pipe setter example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-connections.md Example of receiving a message, creating a new message, and sending it back to the original sender's pipe. ```python # Receive from any peer, send back to that specific peer msg = socket.recv_msg() print(f"From: {msg.pipe.id}") msg = pynng.Message(b'response') msg.pipe = original_msg.pipe socket.send_msg(msg) ``` -------------------------------- ### From Import Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/index.md Importing specific socket classes directly from the pynng library. ```python from pynng import Pair0, Req0, Pub0 s1 = Pair0() s2 = Req0() s3 = Pub0() ``` -------------------------------- ### New Context Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-context-tls.md Example of creating a new context for a socket. ```python context = socket.new_context() ``` -------------------------------- ### Monitoring Options Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/configuration.md Example of retrieving current option values and monitoring connected pipes for a socket. ```python import pynng s = pynng.Pair0(listen='tcp://127.0.0.1:5555') s.dial('tcp://127.0.0.1:5556') # Get current option values print(f"Protocol: {s.protocol_name}") print(f"Local address: {s.local_address}") print(f"Receive timeout: {s.recv_timeout} ms") print(f"Receive buffer: {s.recv_buffer_size} messages") # Monitor pipes for pipe in s.pipes: print(f"Pipe {pipe.id}:") print(f" URL: {pipe.url}") print(f" Remote: {pipe.remote_address}") print(f" Protocol: {pipe.protocol_name}") ``` -------------------------------- ### Message bytes property example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-connections.md Example of receiving a message and accessing its data as bytes. ```python msg = socket.recv_msg() data = msg.bytes print(data) ``` -------------------------------- ### Option Descriptors Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/index.md Shows how socket options can be accessed and modified using attribute-like syntax. ```python s.recv_timeout = 5000 # Set via descriptor value = s.recv_timeout # Get via descriptor ``` -------------------------------- ### Pub0 Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-socket.md Demonstrates publishing messages using a Pub0 socket. ```python pub = pynng.Pub0(listen='tcp://127.0.0.1:5555') pub.send(b'weather:sunny') pub.send(b'weather:rainy') pub.send(b'traffic:clear') ``` -------------------------------- ### Receive and identify sender example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-connections.md Example of receiving a message using recv_msg() and identifying the sender's pipe. ```python import pynng socket = pynng.Pair1( polyamorous=True, listen='tcp://127.0.0.1:5555' ) msg = socket.recv_msg() print(f"Received from pipe {msg.pipe.id}: {msg.bytes}") ``` -------------------------------- ### Req0 Resend Time Option Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/types.md Example demonstrating how to set the resend time for a Req0 socket. ```python req = pynng.Req0() req.resend_time = 2000 # 2 second resend timeout ``` -------------------------------- ### Pair0 Constructor Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-socket.md Demonstrates synchronous and asynchronous communication using Pair0 sockets. ```python from pynng import Pair0 # Synchronous communication with Pair0(listen='tcp://127.0.0.1:54321') as s1, \ Pair0(dial='tcp://127.0.0.1:54321') as s2: s1.send(b'Hello!') print(s2.recv()) # b'Hello!' # Asynchronous communication import trio async def main(): async with Pair0(listen='tcp://127.0.0.1:5555') as s1, \ Pair0(dial='tcp://127.0.0.1:5555') as s2: await s1.asend(b'Async hello') msg = await s2.arecv() print(msg) # b'Async hello' trio.run(main) ``` -------------------------------- ### Standard Import Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/index.md Basic import of the pynng library and instantiation of a Pair0 socket. ```python import pynng s = pynng.Pair0() ``` -------------------------------- ### NoEntry Exception Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/errors.md Shows how to catch the NoEntry exception when a required certificate file is not found. ```python try: tls = pynng.TLSConfig(pynng.TLSConfig.MODE_CLIENT) tls.add_ca_file('/nonexistent/ca.pem') except pynng.NoEntry: print("Certificate file not found") ``` -------------------------------- ### Publisher with custom buffer Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/configuration.md Example of creating a Publisher socket with a custom send buffer size. ```python pub = pynng.Pub0( listen='tcp://127.0.0.1:5555', send_buffer_size=256, # Larger send buffer name='publisher' ) sub = pynng.Sub0( dial='tcp://127.0.0.1:5555', recv_buffer_size=512, # Larger receive buffer recv_max_size=65536, # 64 KB messages topics=['weather', 'news'], name='subscriber' ) ``` -------------------------------- ### NotSupported Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/errors.md Illustrates catching NotSupported when an operation is incompatible with the socket type. ```python pub = pynng.Pub0() try: msg = pub.recv() # Publishers cannot receive except pynng.NotSupported: print("Pub0 sockets do not support recv()") ``` -------------------------------- ### TryAgain Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/errors.md Shows how to handle a TryAgain exception for non-blocking operations. ```python try: data = s.recv(block=False) except pynng.TryAgain: print("No data available right now") ``` -------------------------------- ### Custom Install Function Source: https://github.com/codypiersall/pynng/blob/master/CMakeLists.txt Overrides the default install function to selectively install Python extension modules and source files. ```cmake function(install) # Only allow installing our Python extension module and Python source files if(ARGV0 STREQUAL "TARGETS" AND ARGV1 STREQUAL "_nng") message(STATUS "Installing Python extension module: ${ARGV1}") message(STATUS " Target destination: ${ARGV3}") message(STATUS " Will be installed as: _nng${PYTHON_MODULE_SUFFIX}") _install(${ARGV}) elseif(ARGV0 STREQUAL "DIRECTORY" AND ARGV1 MATCHES ".*pynng/") message(STATUS "Installing Python source files") _install(${ARGV}) else() message(STATUS "Skipping install() for dependency: ${ARGV0} ${ARGV1}") endif() endfunction() ``` -------------------------------- ### PermissionDenied Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/errors.md Shows how to handle PermissionDenied for operations lacking necessary system permissions. ```python try: s = pynng.Pair0(listen='ipc:///root/nng.sock') except pynng.PermissionDenied: print("Insufficient permissions for socket") ``` -------------------------------- ### close Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-socket.md Example of closing a socket. ```python s = pynng.Pair0() s.listen('tcp://127.0.0.1:5555') # ... use socket ... s.close() ``` -------------------------------- ### AddressInUse Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/errors.md Demonstrates catching AddressInUse when trying to listen on an already occupied address. ```python s1 = pynng.Pair0(listen='tcp://127.0.0.1:5555') try: s2 = pynng.Pair0(listen='tcp://127.0.0.1:5555') except pynng.AddressInUse: print("Address is already in use") ``` -------------------------------- ### Socket Attributes (Options) Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-socket.md Example demonstrating how to set and retrieve socket attributes. ```python s = pynng.Pair0() s.recv_timeout = 5000 # 5 second timeout s.name = 'my-socket' print(f"Protocol: {s.protocol_name}") print(f"Buffer size: {s.recv_buffer_size}") ``` -------------------------------- ### recv_msg Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-socket.md Example of receiving a message from a socket. ```python s = pynng.Pair0(listen='tcp://127.0.0.1:5555') msg = s.recv_msg() print(f"From pipe {msg.pipe.id}: {msg.bytes}") ``` -------------------------------- ### CryptoError Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/errors.md Illustrates catching CryptoError during TLS configuration or cryptographic operations. ```python tls = pynng.TLSConfig(pynng.TLSConfig.MODE_CLIENT) tls.set_ca_chain(invalid_pem_data) s = pynng.Pair0(dial='tls+tcp://localhost:8883', tls_config=tls) except pynng.CryptoError: print("TLS setup failed") ``` -------------------------------- ### Modifying setup.cfg to point to local git server Source: https://github.com/codypiersall/pynng/blob/master/docs/developing.md Example configuration changes in setup.cfg to use local git repositories for dependencies. ```cfg [build_nng] repo=git://127.0.0.1:/nanomsg/nng [build_mbedtls] repo=git://127.0.0.1:/Mbed-TLS/mbedtls ``` -------------------------------- ### BadType Exception Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/errors.md Illustrates catching the BadType exception for type mismatches in options. ```python s = pynng.Pair0() try: s.recv_timeout = "1000" # Should be int except pynng.BadType: print("Invalid type for option") ``` -------------------------------- ### Disable mbedTLS Installation Source: https://github.com/codypiersall/pynng/blob/master/CMakeLists.txt Ensures that mbedTLS targets are not installed as part of the build. ```cmake # Disable installation for mbedTLS targets foreach(_target mbedtls_static mbedx509_static mbedcrypto_static everest p256m) if(TARGET ${_target}) set_target_properties(${_target} PROPERTIES EXCLUDE_FROM_ALL TRUE) endif() endforeach() ``` -------------------------------- ### TLS Configuration Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-context-tls.md Demonstrates how to configure TLS for client mode and handle potential errors during configuration and connection. ```python import pynng try: tls = pynng.TLSConfig(pynng.TLSConfig.MODE_CLIENT) # Both must be set together tls.set_own_cert(cert_string, key_string) except ValueError as e: print(f"TLS configuration error: {e}") try: socket = pynng.Pair0( dial='tls+tcp://example.com:8883', tls_config=tls ) except pynng.CryptoError as e: print(f"TLS connection failed: {e}") except pynng.AuthenticationError as e: print(f"TLS authentication failed: {e}") ``` -------------------------------- ### Async Context Manager Support Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-socket.md Example demonstrating the use of a socket with an asynchronous context manager. ```python async with Pair0(listen='tcp://127.0.0.1:5555') as s: # ... use socket in async context ... pass # Socket automatically closed ``` -------------------------------- ### Abstract Socket Example Source: https://github.com/codypiersall/pynng/blob/master/docs/core.md Demonstrates how to create and use an abstract socket on Linux systems, including listening and retrieving the local address. ```python import pynng import platform # Check if we're on Linux if platform.system() != "Linux": print("Abstract sockets are only supported on Linux") exit(1) # Create a socket with abstract address with pynng.Pair0() as sock: # Listen on an abstract socket listener = sock.listen("abstract://my_test_socket") # Get the local address local_addr = listener.local_address print(f"Address family: {local_addr.family_as_str}") print(f"Address name: {local_addr.name}") # The address can be used for dialing from another process # dialer = sock.dial("abstract://my_test_socket") ``` -------------------------------- ### Sub0 Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-socket.md Shows how to subscribe to specific topics using a Sub0 socket and receive messages. ```python sub = pynng.Sub0() sub.subscribe(b'weather') # Receives b'weather:*' messages sub.subscribe(b'') # Receives all messages ``` -------------------------------- ### dial Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-socket.md Examples of dialing a remote address in different modes. ```python s = pynng.Pair0() dialer = s.dial('tcp://localhost:5555') # Hybrid mode dialer = s.dial('tcp://localhost:5555', block=True) # Blocking dialer = s.dial('tcp://localhost:5555', block=False) # Non-blocking ``` -------------------------------- ### Context Manager Support Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-context-tls.md Example of using a context with a 'with' statement for automatic closing. ```python with socket.new_context() as ctx: ctx.send(b'request') response = ctx.recv() # Context automatically closed ``` -------------------------------- ### Cloning dependencies locally and setting up a local git server Source: https://github.com/codypiersall/pynng/blob/master/docs/developing.md Instructions for cloning nng and mbedtls dependencies locally and setting up a git daemon to speed up testing. ```bash # clone *once* locally git clone https://github.com/nanomsg/nng ~/pynng-deps/nanomsg/nng git clone https://github.com/Mbed-TLS/mbedtls ~/pynng-deps/Mbed-TLS/mbedtls # start a git daemon in the parent directory git daemon --reuseaddr --base-path="$HOME/pynng-deps" --export-all ``` -------------------------------- ### Pair1 Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-socket.md Illustrates creating Pair1 sockets in both monogamous and polyamorous modes, and sending/receiving messages. ```python # Single connection (Pair1 in monogamous mode) s = pynng.Pair1() # Multiple connections s = pynng.Pair1(polyamorous=True) s.listen('tcp://127.0.0.1:5555') s.dial('tcp://127.0.0.1:5556') # To send to a specific peer, use Message and Pipe: for msg in s.recv_msg(): msg.pipe.send(b'response') ``` -------------------------------- ### Context Manager Support Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-socket.md Example showing how to use a socket with a synchronous context manager for automatic closing. ```python with Pair0(listen='tcp://127.0.0.1:5555') as s: # ... use socket ... pass # Socket automatically closed ``` -------------------------------- ### InAddr Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/types.md Example demonstrating the use of InAddr for IPv4 socket addresses. ```python s = pynng.Pair0(listen='tcp://127.0.0.1:5555') addr = s.local_address # InAddr print(str(addr)) # '127.0.0.1:5555' print(f"Port: {addr.port}") # Port in network byte order ``` -------------------------------- ### Listener close() Method Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-connections.md Example of closing a listener. ```python listener = s.listen('tcp://127.0.0.1:5555') # ... later ... listener.close() ``` -------------------------------- ### Pipe close() Method Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-connections.md Example of closing a pipe connection. ```python for pipe in socket.pipes: if some_condition(pipe): pipe.close() ``` -------------------------------- ### Send and Receive with Context Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-context-tls.md Example demonstrating synchronous send and receive operations using a context. ```python req = pynng.Req0(dial='tcp://localhost:5555') ctx = req.new_context() ctx.send(b'request data') response = ctx.recv() ``` -------------------------------- ### Setting Options After Creation Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/configuration.md Shows how to set socket options after the socket object has been created but before connecting. ```python import pynng s = pynng.Pair0() # Set options before connecting s.recv_timeout = 5000 s.send_timeout = 5000 s.name = 'my-socket' s.tcp_nodelay = True # Now connect s.listen('tcp://127.0.0.1:5555') # Modify options on listener listener = s.dialers[0] listener.tcp_keepalive = True ``` -------------------------------- ### Context Manager Pattern Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/index.md Demonstrates using a socket as a context manager for automatic cleanup. ```python with Pair0(listen='tcp://127.0.0.1:5555') as s: s.send(b'msg') # Automatically closed ``` -------------------------------- ### OutOfFiles Exception Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/errors.md Illustrates catching the OutOfFiles exception when the system file descriptor limit is reached. ```python try: for i in range(10000): s = pynng.Pair0(listen=f'ipc:///tmp/socket{i}') except pynng.OutOfFiles: print("Reached system file descriptor limit") ``` -------------------------------- ### Secure TLS Connection Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/configuration.md Demonstrates setting up TLS client and server configurations for secure communication. ```python import pynng # TLS client configuration client_tls = pynng.TLSConfig( pynng.TLSConfig.MODE_CLIENT, server_name='example.com', ca_files='/etc/ssl/certs/ca-bundle.crt' ) client = pynng.Pair0( dial='tls+tcp://example.com:8883', tls_config=client_tls, recv_timeout=10000 ) # TLS server configuration server_tls = pynng.TLSConfig( pynng.TLSConfig.MODE_SERVER, cert_key_file='/etc/ssl/certs/server.pem' ) server = pynng.Pair0( listen='tls+tcp://127.0.0.1:8883', tls_config=server_tls ) ``` -------------------------------- ### Bus0 Mesh Networking Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-socket.md Example illustrating the creation of a 3-node mesh network using Bus0 sockets and sending a message to all connected peers. ```python # Create a 3-node mesh bus1 = pynng.Bus0(listen='tcp://127.0.0.1:5555') bus1.dial('tcp://127.0.0.1:5556') bus1.dial('tcp://127.0.0.1:5557') bus2 = pynng.Bus0(listen='tcp://127.0.0.1:5556') bus2.dial('tcp://127.0.0.1:5555') bus2.dial('tcp://127.0.0.1:5557') bus3 = pynng.Bus0(listen='tcp://127.0.0.1:5557') bus3.dial('tcp://127.0.0.1:5555') bus3.dial('tcp://127.0.0.1:5556') # Send from one node to all others bus1.send(b'Message to mesh') ``` -------------------------------- ### set_cert_key_file Method Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-context-tls.md Loads certificate and key from a file. ```python def set_cert_key_file(path, passwd=None) -> None ``` -------------------------------- ### Internal Exception Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/errors.md Example of catching the Internal exception. ```python class Internal(NNGException): """Internal library error""" ``` ```python try: # Some operation that triggers internal error s = pynng.Pair0() except pynng.Internal: print("Internal NNG library error - this is likely a bug") ``` -------------------------------- ### Running CI locally with nektos/act Source: https://github.com/codypiersall/pynng/blob/master/docs/developing.md Command to run GitHub Actions locally using nektos/act for testing CI changes, specifically targeting the cibuildwheel workflow on Ubuntu. ```bash # run cibuildwheel, using ubuntu-20.04 image # This is how you test on Linux # Needs --container-options='-u root' so cibuildwheel can launch its own docker containers act --container-options='-u root' \ -W .github/workflows/cibuildwheel.yml \ --matrix os:ubuntu-20.04 \ --pull=false \ --artifact-server-path=artifacts ``` -------------------------------- ### Concurrent Responses (Rep0) Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-context-tls.md Example demonstrating concurrent handling of requests using multiple contexts with Rep0 sockets. ```python import pynng import asyncio async def main(): rep = pynng.Rep0(listen='tcp://127.0.0.1:5555') # Create contexts for concurrent request handling ctx1 = rep.new_context() ctx2 = rep.new_context() # Handle multiple requests concurrently async def handle_request(ctx): req = await ctx.arecv() print(f"Handling: {req}") await asyncio.sleep(1) # Simulate work await ctx.asend(b'done') tasks = [ handle_request(ctx1), handle_request(ctx2), ] await asyncio.gather(*tasks) asyncio.run(main()) ``` -------------------------------- ### Exception Handling Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/index.md Demonstrates how to handle potential exceptions like timeouts and general NNG errors. ```python import pynng try: s = Pair0(dial='tcp://localhost:5555', recv_timeout=1000) msg = s.recv() except pynng.Timeout: print("Timeout") except pynng.NNGException as e: print(f"NNG Error: {e}") ``` -------------------------------- ### Canceled Exception Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/errors.md Example of catching the Canceled exception during an async operation. ```python class Canceled(NNGException): """Operation was canceled""" ``` ```python import asyncio import pynng async def main(): s = pynng.Pair0() try: task = asyncio.create_task(s.arecv()) task.cancel() await task except asyncio.CancelledError: print("Operation was canceled") ``` -------------------------------- ### Asynchronous Send and Receive with Context Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-context-tls.md Example demonstrating asynchronous send and receive operations using a context. ```python async def asend_receive(ctx): await ctx.asend(b'async request') response = await ctx.arecv() return response ``` -------------------------------- ### ProtocolError Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/errors.md Demonstrates catching a ProtocolError when receiving a malformed message. ```python try: msg = s.recv() except pynng.ProtocolError: print("Received malformed or invalid protocol message") ``` -------------------------------- ### Listener Async Context Manager Support Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/api-reference-connections.md Example of using a listener as an asynchronous context manager. ```python async with socket.listen('tcp://127.0.0.1:5555') as listener: # ... listener is active ... pass # Automatically closed ``` -------------------------------- ### Handling Multiple Peers (Pair1) Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/index.md Example of handling multiple peers with Pair1, including setting up a callback for new pipe connections and sending responses back to the originating peer. ```python import pynng socket = pynng.Pair1(polyamorous=True, listen='tcp://127.0.0.1:5555') peers = {} def on_peer_connect(pipe): peers[pipe.id] = pipe print(f"Peer {pipe.id} connected") socket.add_post_pipe_connect_cb(on_peer_connect) # Receive from any peer, send back to that peer msg = socket.recv_msg() response = pynng.Message(b'response') response.pipe = msg.pipe socket.send_msg(response) ``` -------------------------------- ### Retrieving Error Code Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/errors.md Example of how to retrieve the error code and message from an NNGException. ```python try: s.recv_timeout = -1 except pynng.NNGException as e: error_code = e.errno error_message = str(e) print(f"Error {error_code}: {error_message}") ``` -------------------------------- ### Pipeline with Load Balancing Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/configuration.md Illustrates the Pipeline pattern with a Push socket for distributing work and Pull sockets for workers. ```python import pynng # Work distributor push = pynng.Push0( listen='tcp://127.0.0.1:5555', send_buffer_size=1000, name='job-distributor' ) # Workers (multiple instances of this) pull = pynng.Pull0( dial='tcp://127.0.0.1:5555', recv_buffer_size=10, recv_timeout=30000, reconnect_time_min=100, reconnect_time_max=10000, name='worker' ) ``` -------------------------------- ### AuthenticationError Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/errors.md Demonstrates catching AuthenticationError when TLS peer authentication fails. ```python try: s = pynng.Pair0(dial='tls+tcp://untrusted.example.com:8883') except pynng.AuthenticationError: print("Failed to authenticate peer certificate") ``` -------------------------------- ### AddressInvalid Example Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/errors.md Shows how to catch AddressInvalid for improperly formatted network addresses. ```python try: s = pynng.Pair0(listen='invalid://address:::') except pynng.AddressInvalid: print("Address format is invalid") ``` -------------------------------- ### In-Process Communication Source: https://github.com/codypiersall/pynng/blob/master/_autodocs/configuration.md Demonstrates setting up two sockets within the same process for inter-socket communication. ```python import pynng # Two sockets in the same process s1 = pynng.Pair0( listen='inproc://service', name='server' ) s2 = pynng.Pair0( dial='inproc://service', name='client' ) ```