Skip to main content

Triggers

The ballerina/tcp connector supports event-driven TCP server functionality through a tcp:Listener that accepts inbound connections and dispatches events to your service callbacks. The two-tier service model separates connection-level events (onConnect) from data-level events (onBytes, onError, onClose).

Three components work together:

ComponentRole
tcp:ListenerListens on a local port and accepts inbound TCP connections.
tcp:ServiceHandles the onConnect callback when a new client connects, returning a ConnectionService.
tcp:ConnectionServiceHandles per-connection callbacks: onBytes, onError, and onClose.
tcp:CallerRepresents the connected client within callbacks, providing metadata and the ability to write bytes or close the connection.

For action-based operations, see the Action Reference.


Listener

The tcp:Listener establishes the connection and manages event subscriptions.

Configuration

The listener supports the following connection strategies:

Config TypeDescription
ListenerConfigurationConfiguration for the TCP listener, including the local host binding and optional SSL/TLS settings.

ListenerConfiguration fields:

FieldTypeDefaultDescription
localHoststring()The hostname or IP address to bind the listener to.
secureSocketListenerSecureSocket()SSL/TLS configuration for secure inbound connections.

Initializing the listener

Basic TCP listener:

import ballerina/tcp;

listener tcp:Listener tcpListener = new (3000);

TCP listener with SSL/TLS:

import ballerina/tcp;

listener tcp:Listener tcpListener = new (3000, secureSocket = {
key: {
certFile: "/path/to/server.crt",
keyFile: "/path/to/server.key"
}
});
Generating certificates

For instructions on generating certificates using keytool, see Keystores and Truststores.


Service

A tcp:Service is attached to a tcp:Listener and handles the initial onConnect event. It returns a tcp:ConnectionService that handles the per-connection lifecycle: receiving bytes, handling errors, and reacting to connection closure.

Callback signatures

FunctionSignatureDescription
onConnectremote function onConnect(tcp:Caller caller) returns tcp:ConnectionService|tcp:Error?Invoked when a new TCP client connects. Returns a ConnectionService to handle the connection lifecycle.
onBytesremote function onBytes(readonly & byte[] data) returns byte[]|tcp:Error?Invoked when data is received from the client. Optionally accepts a tcp:Caller as the first parameter. Return bytes to echo data back.
onErrorremote function onError(tcp:Error err) returns tcp:Error?Invoked when an error occurs on the connection.
onCloseremote function onClose() returns tcp:Error?Invoked when the client closes the connection.
note

The onBytes callback is required on every ConnectionService. The onError and onClose callbacks are optional: implement only the events you need.

Full usage example

import ballerina/io;
import ballerina/tcp;

listener tcp:Listener tcpListener = new (3000);

service on tcpListener {
remote function onConnect(tcp:Caller caller) returns tcp:ConnectionService {
io:println("Client connected: ", caller.remoteHost, ":", caller.remotePort);
return new ChatConnectionService();
}
}

service class ChatConnectionService {
*tcp:ConnectionService;

remote function onBytes(tcp:Caller caller, readonly & byte[] data) returns byte[]|tcp:Error? {
string message = check string:fromBytes(data);
io:println("Received: ", message);
// Echo the message back to the client
return data;
}

remote function onError(tcp:Error err) returns tcp:Error? {
io:println("Error: ", err.message());
}

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

Returning a byte[] from onBytes automatically sends those bytes back to the client. This is convenient for echo-style servers. For more control, accept a tcp:Caller as the first parameter and use caller->writeBytes() to send responses explicitly.


Supporting types

Caller

FieldTypeDescription
remoteHoststringThe hostname or IP address of the connected remote client.
remotePortintThe port number of the connected remote client.
localHoststringThe local hostname the listener is bound to.
localPortintThe local port the listener is bound to.
idstringA unique identifier for the connection.

ClientSecureSocket

FieldTypeDescription
enablebooleanEnable or disable SSL. Defaults to true.
certcrypto:TrustStore|stringTrust store configuration or path to the certificate file.
protocolrecord {|Protocol name; string[] versions;|}SSL/TLS protocol configuration.
ciphersstring[]List of cipher suites to use.
handshakeTimeoutdecimalSSL handshake timeout in seconds.
sessionTimeoutdecimalSSL session timeout in seconds.

ListenerSecureSocket

FieldTypeDescription
keycrypto:KeyStore|CertKeyServer key store or certificate and key file paths. Required for SSL/TLS.
protocolrecord {|Protocol name; string[] versions;|}SSL/TLS protocol configuration.
ciphersstring[]List of cipher suites to use. Defaults to [].
handshakeTimeoutdecimalSSL handshake timeout in seconds.
sessionTimeoutdecimalSSL session timeout in seconds.

CertKey

FieldTypeDescription
certFilestringPath to the certificate file.
keyFilestringPath to the private key file in PKCS8 format.
keyPasswordstringPassword for the encrypted private key, if applicable.