Back to Examples

WebSocket service - Send/Receive message

The websocket:Service allows opening up a port via a websocket:Listener. A websocket:Listener is created by giving the port number, to which websocket:Service is attached. The listener accepts and serves connections from WebSocket clients. The onMessage remote method receives incoming WebSocket messages. There are a few other remote methods to receive other types of WebSocket messages. The onOpen remote method is dispatched as soon as the WebSocket handshake is completed and the connection is established, onPing and onPong remote methods are dispatched upon receiving ping and pong messages respectively, onIdleTimeout remote method is dispatched when the idle timeout is reached, onClose is dispatched when a close frame with a statusCode and a reason is received and finally the onError is dispatched when an error occurs in the WebSocket connection. Use this service to implement user applications where you need to establish two-way communication over the WebSocket protocol.

import ballerina/io;
import ballerina/websocket;

service /chat on new websocket:Listener(9090) {

    resource function get .() returns websocket:Service {
        // Accept the WebSocket upgrade by returning a `websocket:Service`.
        return new ChatService();
    }
}

service class ChatService {
    *websocket:Service;

    // This `remote method` is triggered when a new message is received
    // from a client. It accepts `anydata` as the function argument. The received data 
    // will be converted to the data type stated as the function argument.
    remote function onMessage(websocket:Caller caller, string chatMessage) returns error? {
        io:println(chatMessage);
        check caller->writeMessage("Hello!, How are you?");
    }
}

Run the service by executing the command below.

$ bal run websocket_basic_sample.bal

Tip: You can invoke the above service via the WebSocket client.

Related links

PreviousOAuth2 password grant type
NextPayload constraint validation