Skip to main content

Actions

The ballerina/websocket package exposes the following clients:

ClientPurpose
ClientSynchronous WebSocket client for connecting to WebSocket servers and exchanging messages.

For event-driven integration, see the Trigger Reference.


Client

Synchronous WebSocket client for connecting to WebSocket servers and exchanging messages.

Configuration

FieldTypeDefaultDescription
subProtocolsstring[][]Negotiable sub-protocols of the client.
customHeadersmap<string>{}Custom headers to send during the WebSocket handshake.
readTimeoutdecimal-1Read timeout in seconds. -1 means no timeout.
writeTimeoutdecimal-1Write timeout in seconds. -1 means no timeout.
secureSocketClientSecureSocket()SSL/TLS configuration for secure WebSocket (WSS) connections.
maxFrameSizeint65536Maximum payload size of a WebSocket frame in bytes.
webSocketCompressionEnabledbooleantrueEnable support for compression in the WebSocket connection.
handShakeTimeoutdecimal300Time in seconds to wait for the WebSocket handshake response.
authCredentialsConfig|BearerTokenConfig|JwtIssuerConfig|OAuth2GrantConfig()Authentication configuration for the client handshake.
retryConfigWebSocketRetryConfig()Retry configuration for automatic reconnection on connection failure.
validationbooleantrueEnable or disable constraint validation.

Initializing the client

import ballerina/websocket;

websocket:Client wsClient = check new ("ws://localhost:9090/ws");

Operations

Send messages

writeTextMessage

Writes a text message to the WebSocket connection.

Parameters:

NameTypeRequiredDescription
datastringYesText data to be sent.

Returns: error?

Sample code:

check wsClient->writeTextMessage("Hello, WebSocket!");
writeBinaryMessage

Writes binary data to the WebSocket connection.

Parameters:

NameTypeRequiredDescription
databyte[]YesBinary data to be sent.

Returns: error?

Sample code:

byte[] binaryData = "Binary message".toBytes();
check wsClient->writeBinaryMessage(binaryData);
writeMessage

Writes any data to the WebSocket connection. Strings and byte arrays are sent as-is; other types are serialized to JSON.

Parameters:

NameTypeRequiredDescription
dataanydataYesData to be sent. Strings are sent as text frames, byte arrays as binary frames, and other types are JSON-serialized.

Returns: error?

Sample code:

json payload = {event: "greeting", message: "Hello!"};
check wsClient->writeMessage(payload);

Read messages

readTextMessage

Reads a text message from the WebSocket connection in a synchronous (blocking) manner.

Returns: string|error

Sample code:

string textResp = check wsClient->readTextMessage();

Sample response:

"Hello from server!"
readBinaryMessage

Reads binary data from the WebSocket connection in a synchronous (blocking) manner.

Returns: byte[]|error

Sample code:

byte[] binaryResp = check wsClient->readBinaryMessage();

Sample response:

[72, 101, 108, 108, 111]
readMessage

Reads data from the WebSocket connection with automatic data binding to the specified target type.

Parameters:

NameTypeRequiredDescription
targetTypetypedesc<anydata>NoThe expected payload type for data binding.

Returns: targetType|error

Sample code:

json response = check wsClient->readMessage();

Sample response:

{"event": "reply", "message": "Message received"}

Control frames

ping

Sends a ping frame to the WebSocket server.

Parameters:

NameTypeRequiredDescription
databyte[]YesBinary data to include in the ping frame.

Returns: error?

Sample code:

check wsClient->ping("ping".toBytes());
pong

Sends a pong frame to the WebSocket server.

Parameters:

NameTypeRequiredDescription
databyte[]YesBinary data to include in the pong frame.

Returns: error?

Sample code:

check wsClient->pong("pong".toBytes());

Connection management

close

Closes the WebSocket connection with an optional status code and reason.

Parameters:

NameTypeRequiredDescription
statusCodeint?NoStatus code for closing the connection (default 1000 for normal closure).
reasonstring?NoReason string for the closure.
timeoutdecimalNoTime in seconds to wait for the close frame from the remote endpoint. Default is 60. Use -1 to wait indefinitely.

Returns: error?

Sample code:

check wsClient->close();