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.Datagraminherits all methods fromPyjo.EventEmitterand 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_V6ONLYsocket 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_REUSEPORTsocket option, orSO_REUSEADDRon Windows, which has noSO_REUSEPORT.
- property broadcast: bool[source]¶
boolean = datagram.broadcast datagram.broadcast = True
Allow datagrams to a broadcast address, with the
SO_BROADCASTsocket 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 aPyjo.Promiseobject, 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, emittingconnectonce it is connected, orerrorif 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 aPyjo.Promiseobject, which is fulfilled with the socket once it is connected, and rejected with the error of the eventerrorif it cannot be. The socket keeps what arrives forrecv_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.socketobject, orNonebefore 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, whichrecv_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_LOOPorIPV6_MULTICAST_LOOPsocket option.
- property multicast_ttl: int[source]¶
ttl = datagram.multicast_ttl datagram.multicast_ttl = 64
Number of hops of multicast datagrams, with the
IP_MULTICAST_TTLorIPV6_MULTICAST_HOPSsocket option.
- once_p(name: str) Pyjo_Promise[source]¶
promise = datagram.once_p('close')
Same as
once_p()ofPyjo.EventEmitter, but fulfilled at once for the eventcloseof 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,
Nonefor 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
reactorattribute value of the globalPyjo.IOLoopsingleton. 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.Promiseobject, which is fulfilled with the next datagram and the address of its sender, as the eventmessagegives them, orNoneonce the socket is closed, also when it is closed already, and rejected with the error of the eventerror, after which the socket stays open and the next promise waits again, or aTimeoutErrorwhen no datagram has arrived fortimeoutseconds. 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 aPyjo.Promiseobject, which is fulfilled once the datagram has been sent, and rejected with the error of the datagram, in the place of the eventerror, or if the socket is closed before, or is closed already.await datagram.send_p(b'Hello!', ('127.0.0.1', 9999))