macotron.udp
Send UDP datagrams to a host and port, and listen on a local port for datagrams from other devices.
// Answer pings from a device on the LAN.
macotron.udp.listen(9999);
macotron.on("udp:message", ({ host, port, data }) => {
if (data === "ping") macotron.udp.send(host, port, "pong");
});
Sending
send(host: string, port: number, data: string | number[]): { ok: boolean; error?: string }
Sends one datagram over IPv4. host is an IPv4 address or a host name. data is a string, sent as UTF-8, or an array of bytes from 0 to 255. Each call opens a fresh socket, so the datagram leaves from a random local port.
Returns { ok: false, error } when the host does not resolve, the data holds a value that is not a byte, or the send fails.
Broadcast addresses such as 255.255.255.255 do not work: the socket is not set up for broadcast, so the send fails.
// Send three raw bytes to a device on the LAN.
const r = macotron.udp.send("192.168.1.50", 4210, [0x01, 0xff, 0x00]);
if (!r.ok) console.log("send failed:", r.error);
Listening
listen(port: number): { ok: boolean; error?: string }
Binds the port on every IPv4 interface and sends each datagram that arrives as a udp:message event. Listening on a port that is already open returns { ok: true }. Returns { ok: false, error } when the port cannot be bound, for example when another app holds it.
unlisten(port: number): void
Closes the port. Macotron closes every port when plugins reload.
Events
udp:message
Fires for each datagram on a port you listen on. The payload is { host, port, data }. host and port are the sender's address, so you can reply with send(host, port, …). data is the message as a string when it is valid UTF-8, and base64 otherwise. The event does not say which local port received the datagram.
See also
- macotron.bonjour to find a device's host and port.
- macotron.http for HTTP requests.