Skip to content

TCP — Getting Started

Raw TCP connections for custom binary protocols. Use this when HTTP or WebSocket do not fit your use case.


run_tcp_service(port, handler) — Defining a TCP Service

Starts a TCP server on the given port. Each new connection calls your handler with a tcp_connection object.

cpp
#include <framework.hpp>
#include <iostream>

using namespace framework;

int main() {
    framework::app app;

    app.run_tcp_service(9000,
        [](std::shared_ptr<clients::tcp_connection> session) {
            std::cout << "TCP client connected: " << session->get_id() << std::endl;

            session->on_data([](auto session, support::shared_buffer data) {
                std::cout << "Received " << data.size() << " bytes" << std::endl;
                session->send(data);  // echo back
            });

            session->on_close([](auto session) {
                std::cout << "Client disconnected" << std::endl;
            });
        }
    );

    app.run();
    return 0;
}
ParamDescription
portTCP port to listen on.
handlerFunction called for each new connection: (shared_ptr<tcp_connection>).

Reading Strategies

The TCP connection supports three reading strategies, each with an optional timeout.

read_some(timeout) — Read available data

Triggers an asynchronous read. Data is delivered via the on_data callback as soon as any bytes arrive. Does not guarantee a complete message.

cpp
session->read_some();                                          // no timeout
session->read_some(std::chrono::milliseconds(5000));           // 5s timeout

read_fixed(size, timeout) — Read exactly N bytes

Blocks until exactly size bytes are received. Use for protocols with fixed-length headers.

cpp
session->read_fixed(1024);                                     // read 1024 bytes
session->read_fixed(4, std::chrono::milliseconds(5000));       // 4 bytes, 5s timeout

read_until(delimiter, timeout) — Read until delimiter

Reads until a delimiter string is found. Use for line-based protocols.

cpp
session->read_until("\r\n");                                   // read until CRLF
session->read_until("\n", std::chrono::milliseconds(5000));    // read until LF

TCP Connection API

MethodDescription
on_data(handler)Called when data arrives. Handler: (ptr, shared_buffer).
on_error(handler)Called on connection error.
on_close(handler)Called on connection close.
send(buffer)Send data (shared_buffer).
read_some(timeout)Read available data.
read_fixed(size, timeout)Read exactly N bytes.
read_until(delimiter, timeout)Read until delimiter.
set_no_delay(bool)Disable Nagle's algorithm (lower latency).
set_keep_alive(bool)Enable TCP keepalive probes.
get_id()Session UUID.
remote_endpoint()Client address.
get_metrics()Session metrics.
get_state()Access framework state.