Bind a UDP socket (Bun.udpSocket()
)
To create a new (bound) UDP socket:
Send a datagram
Specify the data to send, as well as the destination port and address.send
does not perform
DNS resolution, as it is intended for low-latency operations.
Receive datagrams
When creating your socket, add a callback to specify what should be done when packets are received:Connections
While UDP does not have a concept of a connection, many UDP communications (especially as a client) involve only one peer. In such cases it can be beneficial to connect the socket to that peer, which specifies to which address all packets are sent and restricts incoming packets to that peer only.Send many packets at once using sendMany()
If you want to send a large volume of packets at once, it can make sense to batch them all together to avoid the overhead
of making a system call for each. This is made possible by the sendMany()
API:
For an unconnected socket, sendMany
takes an array as its only argument. Each set of three array elements describes a packet:
The first item is the data to be sent, the second is the target port, and the last is the target address.
sendMany
simply takes an array, where each element represents the data to be sent to the peer.
sendMany
returns the number of packets that were successfully sent. As with send
, sendMany
only takes valid IP addresses
as destinations, as it does not perform DNS resolution.
Handle backpressure
It may happen that a packet that you’re sending does not fit into the operating system’s packet buffer. You can detect that this has happened when:send
returnsfalse
sendMany
returns a number smaller than the number of packets you specified. In this case, thedrain
socket handler will be called once the socket becomes writable again: