ballerina/socket module

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);
    }

    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);
                } else {
                    log:printError("Unable to written the content", err = writeResult);
                }
            } else {
                log:printInfo("Client close: " + caller.remotePort);
            }
        } else {
            log:printError("Unable to read the content", err = result);
        }
    }

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

TCP Client endpoints

Client endpoints are used to connect to and interact with a socket server. The client can only send the data to the server. Client's callbackService needs to retrieve the data from the server and do multiple requests/responses between 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.toByteArray("utf-8");
    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(untaint 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 string | error {
    io:ReadableByteChannel byteChannel = io:createReadableChannel(content);
    io:ReadableCharacterChannel characterChannel = new io:ReadableCharacterChannel(byteChannel, "UTF-8");
    return characterChannel.read(50);
}

UDP Client endpoints

This is a Ballerina UDP client sample. sendTo and receiveFrom action available to interact with 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.toByteArray("utf-8");
    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 = io:createReadableChannel(content);
        io:ReadableCharacterChannel characterChannel = new io:ReadableCharacterChannel(byteChannel, "UTF-8");
        var str = characterChannel.read(60);
        if (str is string) {
            io:println("Received: ", untaint str);
        } else {
            io:println(str.detail().message);
        }
    } else {
        io:println("An error occured while receiving the data ", result);
    }
    var closeResult = socketClient->close();
    if (closeResult is error) {
        io:println("An error occured while closing the connection ", closeResult);
    }
}

Module Detail

Records

Record Description
Address This represent the IP socket address.
ClientConfig Configuration for socket client endpoint.
ListenerConfig Represents the socket server configuration.
SocketError SocketError will return in a socket related error situation.

Objects

Object Description
Listener

Represents service endpoint where socket server service registered and start.

Endpoints

Endpoint Description
Client

Represents socket client and related remote functions.

UdpClient

Represents UDP socket client and related remote functions.

Type Definitions

Type Values Description
Caller Client

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

public type Address

This represent the IP socket address.

Field Name Data Type Default Value Description
host string

The hostname of the Socket Address

port int

The port number of the Socket Address

public type ClientConfig

Configuration for socket client endpoint.

Field Name Data Type Default Value Description
host string

Target service URL

port int

Port number of the remote service

callbackService service

The callback service for the client. Resources in this service gets called on receipt of messages from the server.

public type ListenerConfig

Represents the socket server configuration.

Field Name Data Type Default Value Description
interface string? ()

the interface that server with to bind

public type SocketError

SocketError will return in a socket related error situation.

Field Name Data Type Default Value Description
message string

the cause for the error

public type Listener object

Represents service endpoint where socket server service registered and start.

  • <Listener> __init(int port, socket:ListenerConfig? config)

    Parameter Name Data Type Default Value Description
    port int
    config socket:ListenerConfig? ()
  • <Listener> __start() returns (error?<>)

    Return Type Description
    error?<>
  • <Listener> __stop() returns (error?<>)

    Return Type Description
    error?<>
  • <Listener> __attach(service s, string? name) returns (error?<>)

    Parameter Name Data Type Default Value Description
    s service
    name string? ()
    Return Type Description
    error?<>

Endpoint Client

Represents socket client and related remote functions.

Field Name Data Type Default Value Description
remotePort int 0

the remote port number to which this socket is connected

localPort int 0

the local port number to which this socket is bound

remoteAddress string? ()

the remote IP address string in textual presentation to which the socket is connected

localAddress string? ()

the local IP address string in textual presentation to which the socket is bound

id int 0

a unique identifier to identify each client

  • <Client> write(byte[] content) returns (int|error<>)

    Writes given data to the client socket.

    Parameter Name Data Type Default Value Description
    content byte[]
    • the content that wish to send to the client socket
    Return Type Description
    int|error<>
    • number of bytes got written or an error if encounters an error while writing
  • <Client> read(int length) returns ((byte[],int)|error<>)

    Reads data from the client socket. If the data has the specified length, then wait until that number of bytes are received from the client. Else, return the data available in the OS buffer. In the case of the connection being closed by the client, then return either -1 or the data that is currently available in the buffer. Number of bytes returned will be < 0 if the client closes the connection.

    Parameter Name Data Type Default Value Description
    length int -100
    • Positive integer. Represents the number of bytes which should be read
    Return Type Description
    (byte[],int)|error<>
    • Content as a byte array and the number of bytes read or an error if encounters an error while reading
  • <Client> close() returns (error?<>)

    Closes the client socket connection.

    Return Type Description
    error?<>
    • an error if encounters an error while closing the connection or returns nil otherwise
  • <Client> shutdownRead() returns (error?<>)

    Shutdowns the further read from socket.

    Return Type Description
    error?<>

    an error if encounters an error while shutdown the read from socket or returns nil otherwise

  • <Client> shutdownWrite() returns (error?<>)

    Shutdowns the further write from socket.

    Return Type Description
    error?<>

    an error if encounters an error while shutdown the write from socket or returns nil otherwise

Endpoint UdpClient

Represents UDP socket client and related remote functions.

Field Name Data Type Default Value Description
localPort int 0

the local port number to which this socket is bound

interface string? ()

network interface to bind to

id int 0

a unique identifier to identify each client

  • <UdpClient> sendTo(byte[] content, socket:Address address) returns (int|error<>)

    Send given data to the specified remote client.

    Parameter Name Data Type Default Value Description
    content byte[]

    the content that wish to send to the client socket

    address socket:Address

    the address of the remote client socket

    Return Type Description
    int|error<>

    number of bytes got written or an error if encounters an error while writing

  • <UdpClient> receiveFrom(int length) returns ((byte[],int,Address)|error<>)

    Reads data from the remote client. If the data has the specified length, then wait until that number of bytes are received from the client. Else, return the data available in the OS buffer or wait until data receive. If the request length is lesser than the data in the buffer, then the rest will be discarded.

    Parameter Name Data Type Default Value Description
    length int -100

    Positive integer. Represents the number of bytes which should be read

    Return Type Description
    (byte[],int,Address)|error<>

    Content as a byte array, the number of bytes read and the address of the sender or an error if encounters an error while reading

  • <UdpClient> close() returns (error?<>)

    Closes the client socket connection.

    Return Type Description
    error?<>
    • an error if encounters an error while closing the connection or returns nil otherwise