Pyjo.IOLoop.Datagram - Non-blocking datagram socket

from Pyjo.IOLoop.Datagram import Datagram

# Echo server
server = Datagram()
server.on('message', lambda server, data, peer: server.send(b'Echo: ' + data, peer))
server.bind(address='127.0.0.1', port=9999)

# Or import the module, as in Google Python Style Guide

import Pyjo.IOLoop.Datagram

# Echo server
server = Pyjo.IOLoop.Datagram.new()
server.on('message', lambda server, data, peer: server.send(b'Echo: ' + data, peer))
server.bind(address='127.0.0.1', port=9999)

# Client
client = Pyjo.IOLoop.Datagram.new()
client.on('message', lambda client, data, peer: print(data))
client.on('error', lambda client, err: print(err))
client.send(b'Hello!', ('127.0.0.1', 9999))

# Start reactor if necessary
if not client.reactor.is_running:
    client.reactor.start()

Pyjo.IOLoop.Datagram is a container for datagram sockets used by Pyjo.IOLoop: UDP over IPv4 and IPv6, and UNIX domain datagram sockets. Every send() is one datagram, and every message event is one datagram that has arrived.

A socket that is neither bound with bind() nor connected with connect() is bound to a random port by the first send(), as the family of the address of the peer needs it.

The end of a with block closes the socket.

Events

Pyjo.IOLoop.Datagram inherits all events from Pyjo.EventEmitter and can emit the following new ones.

close

datagram.on('close', lambda datagram: ...)

Emitted if the socket gets closed.

connect

datagram.on('connect', lambda datagram: ...)

Emitted once the socket has been connected with connect().

error

datagram.on('error', lambda datagram, err: ...)

Emitted if an error occurs on the socket, fatal if unhandled. The error is the OSError of the handle, as a datagram that cannot be sent or the refusal of a peer that a connected socket gets, or a message for a name that cannot be resolved. The socket stays open.

message

datagram.on('message', lambda datagram, data, peer: ...)

Emitted for every datagram that arrives, with the address of its sender, as socket.socket.recvfrom() gives it, which send() takes as the address of a reply.

See also

Pyjoyment, https://mojolicious.org.

Inspired by dgram of Node.js, as Mojolicious has no datagram sockets.

class Pyjo.IOLoop.Datagram.Pyjo_IOLoop_Datagram(handle: socket | None = None)[source]

Pyjo.IOLoop.Datagram inherits all methods from Pyjo.EventEmitter and implements the following new ones.

add_membership(group: str, interface: str | int | None = None) → Self[source]
datagram = datagram.add_membership('224.0.0.114')
datagram = datagram.add_membership('224.0.0.114', '192.168.1.1')
datagram = datagram.add_membership('ff02::114', 'eth0')

Join a multicast group, on the interface with the address for IPv4, or the name or the index for IPv6, or on the one that the system chooses.

bind(**options: Any) → Self[source]
datagram = datagram.bind(port=9999)

Bind the socket to a local address, and start receiving datagrams.

These options are currently available:

address
address='127.0.0.1'

Local address to bind to, defaults to 0.0.0.0.

ipv6_only
ipv6_only=True

Receive only IPv6 datagrams on an IPv6 address, with the IPV6_V6ONLY socket option.

path
path='/tmp/myapp.sock'

Path for UNIX domain datagram socket to bind to.

port
port=9999

Port to bind to, defaults to a random port.

reuse
reuse=True

Allow multiple sockets to use the same port with the SO_REUSEPORT socket option, or SO_REUSEADDR on Windows, which has no SO_REUSEPORT.

property broadcast: bool[source]
boolean = datagram.broadcast
datagram.broadcast = True

Allow datagrams to a broadcast address, with the SO_BROADCAST socket option.

property bytes_waiting: int[source]
num = datagram.bytes_waiting

Number of bytes of the datagrams that have been enqueued with send() and are waiting to be sent.

close() → None[source]
datagram.close()

Close socket immediately, the datagrams that wait to be sent are dropped.

close_gracefully() → None[source]
datagram.close_gracefully()

Close socket once the datagrams that wait have been sent.

close_gracefully_p() → Pyjo_Promise[source]
promise = datagram.close_gracefully_p()

Same as close_gracefully(), but returns a Pyjo.Promise object, which is fulfilled once the socket has been closed, also when it is closed already, or has never been opened.

await datagram.send_p(b'Bye!')
await datagram.close_gracefully_p()
connect(**options: Any) → Self[source]
datagram = datagram.connect(address='127.0.0.1', port=9999)

Connect the socket to a peer, so that send() needs no address and only the datagrams of the peer arrive, emitting connect once it is connected, or error if it cannot be. A name is resolved without blocking.

These options are currently available:

address
address='mojolicious.org'

Address or host name of the peer to connect to, defaults to 127.0.0.1.

path
path='/tmp/myapp.sock'

Path of UNIX domain datagram socket to connect to.

port
port=9999

Port to connect to.

connect_p(**options: Any) → Pyjo_Promise[source]
promise = datagram.connect_p(address='127.0.0.1', port=9999)

Same as connect(), but returns a Pyjo.Promise object, which is fulfilled with the socket once it is connected, and rejected with the error of the event error if it cannot be. The socket keeps what arrives for recv_p() from then on, also the refusal of the peer, as a coroutine that awaits the promise goes on later.

datagram = await Pyjo.IOLoop.Datagram.new().connect_p(address='127.0.0.1', port=9999)
await datagram.send_p(b'Hello!')
drop_membership(group: str, interface: str | int | None = None) → Self[source]
datagram = datagram.drop_membership('224.0.0.114')

Leave a multicast group, with the same arguments as add_membership().

property handle: socket | None[source]
handle = datagram.handle

Get handle for socket, a socket.socket object, or None before it is bound.

iterate() → Pyjo.Iterator.object[tuple[bytes, Any]][source]
async for data, peer in datagram.iterate():
    ...

The datagrams that arrive as a Pyjo.Iterator, with the address of their sender, until the socket is closed, which recv_p() takes.

# Echo server, one datagram after another
async for data, peer in datagram:
    await datagram.send_p(b'Echo: ' + data, peer)

# The datagrams of one peer, in a chain
async for data, peer in datagram.iterate().grep(lambda message: message[1] == trusted):
    ...
property multicast_loopback: bool[source]
boolean = datagram.multicast_loopback
datagram.multicast_loopback = False

Receive the multicast datagrams that the socket sends, with the IP_MULTICAST_LOOP or IPV6_MULTICAST_LOOP socket option.

property multicast_ttl: int[source]
ttl = datagram.multicast_ttl
datagram.multicast_ttl = 64

Number of hops of multicast datagrams, with the IP_MULTICAST_TTL or IPV6_MULTICAST_HOPS socket option.

once_p(name: str) → Pyjo_Promise[source]
promise = datagram.once_p('close')

Same as once_p() of Pyjo.EventEmitter, but fulfilled at once for the event close of a socket that is closed already, as it comes no more.

property port: int | None[source]
port = datagram.port

Get port the socket is bound to, None for a UNIX domain socket or before it is bound.

property reactor: Pyjo_Reactor[source]
reactor = datagram.reactor
datagram.reactor = Pyjo.Reactor.Poll.new()

Low-level event reactor, defaults to the reactor attribute value of the global Pyjo.IOLoop singleton. Note that this attribute is weakened.

recv_p(timeout: float | None = None) → Pyjo_Promise[source]
promise = datagram.recv_p()
promise = datagram.recv_p(timeout=5)

Return a Pyjo.Promise object, which is fulfilled with the next datagram and the address of its sender, as the event message gives them, or None once the socket is closed, also when it is closed already, and rejected with the error of the event error, after which the socket stays open and the next promise waits again, or a TimeoutError when no datagram has arrived for timeout seconds. The socket reads only while a promise waits, and the datagrams that arrive before wait in the socket, as the streams do.

if (received := await datagram.recv_p()) is not None:
    data, peer = received
    print(f'{data!r} from {peer}')
send(data: bytes, peer: Peer | None = None, cb: SendCallback | None = None) → Self[source]
datagram = datagram.send(b'Hello!')
datagram = datagram.send(b'Hello!', ('127.0.0.1', 9999))
datagram = datagram.send(b'Hello!', ('localhost', 9999), lambda datagram: ...)
datagram = datagram.send(b'Hello!', '/tmp/myapp.sock')

Enqueue a datagram to be sent as soon as possible, to the peer of connect(), or to the address given to a socket that is not connected, whose name is resolved without blocking. The optional callback will be executed once the datagram has been sent.

send_p(data: bytes, peer: Peer | None = None) → Pyjo_Promise[source]
promise = datagram.send_p(b'Hello!')
promise = datagram.send_p(b'Hello!', ('127.0.0.1', 9999))

Same as send(), but returns a Pyjo.Promise object, which is fulfilled once the datagram has been sent, and rejected with the error of the datagram, in the place of the event error, or if the socket is closed before, or is closed already.

await datagram.send_p(b'Hello!', ('127.0.0.1', 9999))
start() → None[source]
datagram.start()

Start or resume watching for new datagrams on the socket.

stop() → None[source]
datagram.stop()

Stop watching for new datagrams on the socket.

property ttl: int[source]
ttl = datagram.ttl
datagram.ttl = 64

Number of hops of unicast datagrams, with the IP_TTL or IPV6_UNICAST_HOPS socket option.