Actions
The ballerina/udp package exposes the following clients:
| Client | Purpose |
|---|---|
Client | Sends and receives UDP datagrams without a fixed remote host connection. |
Connect Client | Sends and receives UDP data to/from a fixed remote host and port. |
For event-driven integration, see the Trigger Reference.
Client
Sends and receives UDP datagrams without a fixed remote host connection.
Configuration
| Field | Type | Default | Description |
|---|---|---|---|
timeout | decimal | 300 | Socket read timeout in seconds. |
localHost | string | () | Local network interface to bind the socket to. |
Initializing the client
import ballerina/udp;
udp:Client udpClient = check new ();
Operations
Datagram operations
sendDatagram
Sends a datagram to a specified remote host and port.
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
datagram | Datagram | Yes | The datagram containing remoteHost, remotePort, and data fields. |
Returns: Error?
Sample code:
check udpClient->sendDatagram({
remoteHost: "localhost",
remotePort: 8080,
data: "Hello from UDP client".toBytes()
});
receiveDatagram
Receives a datagram from any remote host. Blocks until data arrives or the timeout is reached.
Returns: readonly & Datagram|Error
Sample code:
udp:Datagram datagram = check udpClient->receiveDatagram();
Sample response:
{"remoteHost": "localhost", "remotePort": 8080, "data": [72, 101, 108, 108, 111]}
close
Closes the UDP client socket and frees the associated resources.
Returns: Error?
Sample code:
check udpClient->close();
Connect client
Sends and receives UDP data to/from a fixed remote host and port.
Configuration
| Field | Type | Default | Description |
|---|---|---|---|
timeout | decimal | 300 | Socket read timeout in seconds. |
localHost | string | () | Local network interface to bind the socket to. |
Initializing the client
import ballerina/udp;
udp:ConnectClient udpConnectClient = check new ("localhost", 8080);
Operations
Byte operations
writeBytes
Sends bytes to the connected remote host. If the data exceeds the maximum datagram size, it is sent across multiple datagrams.
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
data | byte[] | Yes | The byte array to send. |
Returns: Error?
Sample code:
check udpConnectClient->writeBytes("Hello from connected client".toBytes());
readBytes
Reads bytes from the connected remote host. Blocks until data arrives or the timeout is reached.
Returns: readonly & byte[]|Error
Sample code:
byte[] received = check udpConnectClient->readBytes();
Sample response:
[72, 101, 108, 108, 111]
close
Closes the connected UDP client socket and frees the associated resources.
Returns: Error?
Sample code:
check udpConnectClient->close();