import ballerina/io;
import ballerina/log;
import ballerina/tcp;

// Bind the service to the port. 
service on new tcp:Listener(3000) {

    // This remote method is invoked when the new client connects to the server.
    remote function onConnect(tcp:Caller caller)
                              returns tcp:ConnectionService {
        io:println("Client connected to echo server: ", caller.remotePort);
        return new EchoService();
    }
}

service class EchoService {

    // This remote method is invoked once the content is received from the client.
    remote function onBytes(tcp:Caller caller, readonly & byte[] data) 
        returns tcp:Error? {
        io:println("Echo: ", string:fromBytes(data));
        // Echoes back the data to the client from which the data is received.
        check caller->writeBytes(data);
    }

    // This remote method is invoked in an erroneous situation,
    // which occurs during the execution of the `onConnect` or `onBytes` method.
    remote function onError(tcp:Error err) returns tcp:Error? {
        log:printError("An error occurred", 'error = err);
    }

    // This remote method is invoked when the connection is closed.
    remote function onClose() returns tcp:Error? {
        io:println("Client left");
    }
}

TCP Listener

The TCP Listener is used to expose a TCP service over the TCP protocol. This sample demonstrates how the TCP socket listener service interacts with the TCP client.

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

import ballerina/io;
import ballerina/log;
import ballerina/tcp;
service on new tcp:Listener(3000) {

Bind the service to the port.

    remote function onConnect(tcp:Caller caller)
                              returns tcp:ConnectionService {
        io:println("Client connected to echo server: ", caller.remotePort);
        return new EchoService();
    }
}

This remote method is invoked when the new client connects to the server.

service class EchoService {
    remote function onBytes(tcp:Caller caller, readonly & byte[] data) 
        returns tcp:Error? {
        io:println("Echo: ", string:fromBytes(data));

This remote method is invoked once the content is received from the client.

        check caller->writeBytes(data);
    }

Echoes back the data to the client from which the data is received.

    remote function onError(tcp:Error err) returns tcp:Error? {
        log:printError("An error occurred", 'error = err);
    }

This remote method is invoked in an erroneous situation, which occurs during the execution of the onConnect or onBytes method.

    remote function onClose() returns tcp:Error? {
        io:println("Client left");
    }
}

This remote method is invoked when the connection is closed.

bal run tcp_listener.bal
Client connected to echoServer: 48735
Echo: Hello Ballerina Echo from client
Client left