import ballerina/io;
import ballerina/log;
import ballerina/websocket;

@websocket:ServiceConfig {
    subProtocols: ["xml", "json"],
    idleTimeout: 120
}
service /basic/ws on new websocket:Listener(9090) {
   resource isolated function get .()
                     returns websocket:Service|websocket:UpgradeError {
       // Accept the WebSocket upgrade by returning a `websocket:Service`.
       return new WsService();
   }
}

service class WsService {
    *websocket:Service;
    // This `remote function` is triggered when a new text message is received
    // from a client.
    remote isolated function onTextMessage(websocket:Caller caller,
                                 string text) {
        io:println("\ntext message: " + text);
        websocket:Error? err = caller->writeTextMessage("You said: " + text);
        if err is websocket:Error {
            log:printError("Error occurred when sending text", 'error = err);
        }
    }
}

Listener Functionalities

This example explains the basic functions of a WebSocket server.

For more information on the underlying module, see the WebSocket module.

import ballerina/io;
import ballerina/log;
import ballerina/websocket;
@websocket:ServiceConfig {
    subProtocols: ["xml", "json"],
    idleTimeout: 120
}
service /basic/ws on new websocket:Listener(9090) {
   resource isolated function get .()
                     returns websocket:Service|websocket:UpgradeError {
       return new WsService();
   }
}

Accept the WebSocket upgrade by returning a websocket:Service.

service class WsService {
    *websocket:Service;
    remote isolated function onTextMessage(websocket:Caller caller,
                                 string text) {
        io:println("\ntext message: " + text);
        websocket:Error? err = caller->writeTextMessage("You said: " + text);
        if err is websocket:Error {
            log:printError("Error occurred when sending text", 'error = err);
        }
    }
}

This remote function is triggered when a new text message is received from a client.

bal run websocket_basic_sample.bal
# To check the sample, use a Chrome or Firefox JavaScript console and run the commands below. <br>
# Change `xml` to another sub protocol to observe the behavior of the WebSocket server.
var ws = new WebSocket("ws://localhost:9090/basic/ws", "xml", "my-protocol");
ws.onmessage = function(frame) {console.log(frame.data)};
ws.onclose = function(frame) {console.log(frame)};
# Send a message.
ws.send("hello world");