Skip to content

TCP — Custom Handlers

Build structured request-response protocols on top of raw TCP sessions.


Request-Response Protocol Example

Parse a binary header, process the payload, and send a response.

cpp
using namespace framework;
using namespace framework::support;

app.run_tcp_service(9000,
    [](std::shared_ptr<clients::tcp_connection> session) {
        session->on_data([](auto session, shared_buffer data) {
            // Parse fixed-length header (8 bytes)
            if (data.size() < 8) return;

            uint32_t request_id = ntohl(*reinterpret_cast<const uint32_t*>(data.data()));
            uint32_t payload_len = ntohl(*reinterpret_cast<const uint32_t*>(data.data() + 4));

            if (data.size() < 8 + payload_len) return;

            // Process and build response
            std::vector<uint8_t> response(8 + payload_len);
            *reinterpret_cast<uint32_t*>(response.data()) = htonl(request_id);
            *reinterpret_cast<uint32_t*>(response.data() + 4) = htonl(payload_len);
            std::memcpy(response.data() + 8, data.data() + 8, payload_len);

            session->send(shared_buffer::make(std::move(response)));
        });
    }
);

Connection Lifecycle

PhaseWhat Happens
Acceptrun_tcp_service() accepts the connection and calls your handler.
DataData arrives via on_data callback. You parse and respond.
CloseClient disconnects or you call session->stop().
CleanupThe on_close callback fires. Resources are released automatically.

Combining with Other Protocols

TCP, HTTP, and WebSocket services coexist on the same node. Each listens on its own port:

cpp
app.run_tcp_service(9000, tcp_handler);       // Custom binary protocol
app.run_http_service(8080);                    // REST API
app.run_websocket_service(8081);               // Real-time WebSocket

app.run();  // All three run concurrently