Module : socket

Module overview

This module provides an implementation for connecting to a remote socket server or acts as a server for an incoming socket request. The module facilitates two types of endpoints called Client and Listener.

Samples

TCP Listener endpoints

The sample given below shows how a listener is used to listen to the incoming socket request. The onConnect(socket:Caller) resource function gets invoked when a new client is connected. The new client is represented using the socket:Caller. onReadReady(socket:Caller) resource gets invoked once the remote client sends some data.

import ballerina/log;
import ballerina/socket;

listener socket:Listener server = new(61598);

service echoServer on server {
    resource function onConnect(socket:Caller caller) {
        log:printInfo("Join: " + caller.remotePort.toString());
    }

    resource function onReadReady(socket:Caller caller) {
        var result = caller->read();
        if (result is [byte[], int]) {
            var [content, length] = result;
            if (length > 0) {
                var writeResult = caller->write(content);
                if (writeResult is int) {
                    log:printInfo("Number of bytes written: " 
                                    + writeResult.toString());
                } else {
                    log:printError("Unable to written the content", writeResult);
                }
            } else {
                log:printInfo("Client close: " + caller.remotePort.toString());
            }
        } else {
            log:printError("Unable to read the content", result);
        }
    }

    resource function onError(socket:Caller caller, error er) {
        log:printError("An error occurred", er);
    }
}

TCP Client endpoints

The client endpoint is used to connect to and interact with a socket server. The client can only send the data to the server. The client's callbackService needs to retrieve the data from the server and do multiple requests/responses between the client and the server.

import ballerina/io;
import ballerina/socket;

public function main() {
    socket:Client socketClient = new({ host: "localhost", 
                                       port: 61598, 
                                       callbackService: ClientService });
    string msg = "Hello Ballerina\n";
    byte[] c1 = msg.toBytes();
    var writeResult = socketClient->write(c1);
    if (writeResult is int) {
        io:println("Number of bytes written: " , writeResult);
    } else {
        io:println("Unable to written the content", 
                        writeResult.detail()["message"]);
    }
}

service ClientService = service {

    resource function onConnect(socket:Caller caller) {
        io:println("connect: ", caller.remotePort);
    }
    
    resource function onReadReady(socket:Caller caller) {
        var result = caller->read();
        if (result is [byte[], int]) {
            var [content, length] = result;
            if (length > 0) {
                var str = getString(content);
                if (str is string) {
                    io:println(<@untainted> str);
                } else {
                    io:println(str.reason());
                }
                var closeResult = caller->close();
                if (closeResult is error) {
                    io:println(closeResult.detail()["message"]);
                } else {
                    io:println("Client connection closed successfully.");
                }
            } else {
                io:println("Client close: ", caller.remotePort);
            }
        } else {
            io:println(result);
        }
    }
    
    resource function onError(socket:Caller caller, error er) {
        io:println(er.reason());
    }
};

function getString(byte[] content) returns @tainted string | error {
    io:ReadableByteChannel byteChannel = check io:createReadableChannel(content);
    io:ReadableCharacterChannel 
         characterChannel = new io:ReadableCharacterChannel(byteChannel, "UTF-8");
    return characterChannel.read(50);
}

UDP Client endpoints

UDP client endpoint is used to interact with the remote UDP host.

import ballerina/io;
import ballerina/socket;

public function main() {
    socket:UdpClient socketClient = new;
    string msg = "Hello from UDP client";
    byte[] c1 = msg.toBytes();
    var sendResult =
        socketClient->sendTo(c1, { host: "localhost", port: 48826 });
    if (sendResult is int) {
        io:println("Number of bytes written: ", sendResult);
    } else {
        panic sendResult;
    }
    var result = socketClient->receiveFrom();
    if (result is [byte[], int, socket:Address]) {
        var [content, length, address] = result;
        io:ReadableByteChannel byteChannel 
                = checkpanic io:createReadableChannel(content);
        io:ReadableCharacterChannel characterChannel 
                = new io:ReadableCharacterChannel(byteChannel, "UTF-8");
        var str = characterChannel.read(60);
        if (str is string) {
            io:println("Received: ", <@untainted> str);
        } else {
            io:println(str.detail()["message"]);
        }
    } else {
        io:println("An error occurred while receiving the data ", result);
    }
    var closeResult = socketClient->close();
    if (closeResult is error) {
        io:println("An error occurred while closing the connection ", 
                    closeResult);
    }
}

Records

Address This represent the IP socket address.
ClientConfig Configuration for socket client endpoint.
ListenerConfig Represents the socket server configuration.
UdpClientConfig Configuration for UDP client.

Clients

Client

Represents socket client and related remote functions.

UdpClient

Represents UDP socket client and related remote functions.

Listeners

Listener

Represents service endpoint where socket server service registered and start.

Constants

READ_TIMED_OUT

This will used to construct a ReadTimedOutError.

GENERIC_ERROR

This will used to construct a GENERIC_ERROR.

Types

Caller

Represents caller object in socket service resources and client callback service resources. This has all the remote functions expose by socket:Client.

Error

Represents socket module related errors.

Errors

GenericError

Represents generic socket error. The detail record contains the information related to the error.

ReadTimedOutError

This will returns once the given read timed out time exceed for socket reads.