Skip to main content

Triggers

The ballerina/websocket connector supports building WebSocket servers using a websocket:Listener and websocket:Service combination. The listener accepts incoming WebSocket connections via an HTTP upgrade handshake, and the service defines callbacks for handling messages, connection lifecycle events, and control frames.

Three components work together:

ComponentRole
websocket:ListenerListens on a port for incoming HTTP upgrade requests and establishes WebSocket connections.
websocket:UpgradeServiceHandles the initial HTTP upgrade request and returns a websocket:Service to handle the WebSocket connection.
websocket:ServiceDefines callbacks (onOpen, onMessage, onClose, etc.) invoked for each WebSocket connection event.
websocket:CallerRepresents the remote WebSocket client within service callbacks, used to send messages back and manage the connection.

For action-based operations, see the Action Reference.


Listener

The websocket:Listener establishes the connection and manages event subscriptions.

Configuration

The listener supports the following connection strategies:

Config TypeDescription
ListenerConfigurationConfiguration for the WebSocket listener endpoint.

ListenerConfiguration fields:

FieldTypeDefaultDescription
hoststring"0.0.0.0"The host name or IP address of the listener endpoint.
secureSocketListenerSecureSocket()SSL/TLS configuration for secure WebSocket (WSS) server.
timeoutdecimal120Period of time in seconds that a connection waits for a read/write operation during the initial upgrade request. Use 0 to disable.
serverstring?()The server name to appear in the response header.
webSocketCompressionEnabledbooleantrueEnable support for compression in WebSocket.
http1SettingsListenerHttp1Settings{}Configurations related to HTTP/1.x protocol.
requestLimitsRequestLimitConfigs{}Configurations for inbound request size limits.

Initializing the listener

Using a port number:

import ballerina/websocket;

listener websocket:Listener wsListener = new (9090);

Using a port number with configuration:

import ballerina/websocket;

listener websocket:Listener wsListener = new (9090, {
secureSocket: {
key: {
certFile: "/path/to/cert.pem",
keyFile: "/path/to/key.pem"
}
}
});

Using an existing HTTP listener:

import ballerina/http;
import ballerina/websocket;

listener http:Listener httpListener = new (9090);
listener websocket:Listener wsListener = new (httpListener);

Service

A websocket:Service is a Ballerina service class that implements callbacks for WebSocket connection events. It is returned by the websocket:UpgradeService resource function during the HTTP-to-WebSocket upgrade handshake. Each client connection gets its own service instance.

Callback signatures

FunctionSignatureDescription
onOpenremote function onOpen(websocket:Caller caller) returns error?Invoked when a new WebSocket connection is established.
onTextMessageremote function onTextMessage(websocket:Caller caller, string text) returns error?Invoked when a text message is received from the client.
onBinaryMessageremote function onBinaryMessage(websocket:Caller caller, byte[] data) returns error?Invoked when a binary message is received from the client.
onMessageremote function onMessage(websocket:Caller caller, anydata data) returns error?Invoked when any message is received. Use this instead of onTextMessage/onBinaryMessage for generic or typed message handling.
onPingremote function onPing(websocket:Caller caller, byte[] data) returns error?Invoked when a ping frame is received from the client.
onPongremote function onPong(websocket:Caller caller, byte[] data) returns error?Invoked when a pong frame is received from the client.
onIdleTimeoutremote function onIdleTimeout(websocket:Caller caller) returns error?Invoked when the connection remains idle beyond the configured idleTimeout.
onCloseremote function onClose(websocket:Caller caller, int statusCode, string reason) returns error?Invoked when the client closes the connection.
onErrorremote function onError(websocket:Caller caller, error err) returns error?Invoked when an error occurs during the connection.
note

You do not need to implement all callbacks. Only implement the event types relevant to your use case. For example, a simple chat server may only need onOpen, onMessage, and onClose.

Full usage example

import ballerina/io;
import ballerina/websocket;

map<websocket:Caller> connectionsMap = {};

service /chat on new websocket:Listener(9090) {
resource function get [string username]() returns websocket:Service|websocket:UpgradeError {
return new ChatServer(username);
}
}

service class ChatServer {
*websocket:Service;

string username;

public function init(string username) {
self.username = username;
}

remote function onOpen(websocket:Caller caller) returns error? {
string welcomeMsg = "Hi " + self.username + "! You have successfully connected to the chat";
check caller->writeMessage(welcomeMsg);
string msg = self.username + " connected to chat";
check broadcast(msg);
lock {
connectionsMap[caller.getConnectionId()] = caller;
}
}

remote function onMessage(websocket:Caller caller, string text) returns error? {
string msg = self.username + ": " + text;
io:println(msg);
check broadcast(msg);
}

remote function onClose(websocket:Caller caller, int statusCode, string reason) returns error? {
lock {
_ = connectionsMap.remove(caller.getConnectionId());
}
string msg = self.username + " left the chat";
check broadcast(msg);
}
}

function broadcast(string text) returns error? {
foreach websocket:Caller con in connectionsMap {
check con->writeMessage(text);
}
}
note

The websocket:UpgradeService resource function get handles the HTTP-to-WebSocket upgrade. The resource path segments become part of the URL pattern (e.g., service /chat on wsListener listens at /chat). Path parameters in the resource function (e.g., get [string username]()) allow extracting values from the URL.


Supporting types

WSServiceConfig

FieldTypeDescription
subProtocolsstring[]Negotiable sub-protocols for the service.
idleTimeoutdecimalIdle timeout in seconds for client connections. Triggers onIdleTimeout callback on expiry. Default is 0 (disabled).
maxFrameSizeintMaximum payload size of a WebSocket frame in bytes. Default is 65536.
authListenerAuthConfig[]Listener authentication configurations (Basic Auth, JWT, OAuth2 introspection).
validationbooleanEnable or disable constraint validation. Default is true.
dispatcherKeystringThe JSON key used for dispatching messages to custom remote functions.
dispatcherStreamIdstringIdentifier used to distinguish between requests and responses in multiplexing scenarios.
connectionClosureTimeoutdecimalTime in seconds to wait for the close frame from the remote endpoint. Default is 60.

WebSocketRetryConfig

FieldTypeDescription
maxCountintMaximum number of retry attempts. 0 means retry indefinitely.
intervaldecimalDelay in seconds before attempting to reconnect. Default is 1.
backOffFactorfloatRate of increase of the reconnect delay. Default is 1.0.
maxWaitIntervaldecimalMaximum retry interval in seconds. Default is 30.

CloseFrame

FieldTypeDescription
statusintThe WebSocket close status code (e.g., 1000 for normal closure, 1001 for going away).
reasonstring?Optional reason string for the closure.