47 / Networking

TCP Server

A minimal TCP echo server using built-in primitives. tcp_listen binds to a port, tcp_accept waits for a client connection, then you read and write data on the client socket. This is the foundation for all Nyx network servers.

47-tcp-server.nxSource →
// TCP echo server — listen, accept, echo back
// Servidor TCP echo — escuchar, aceptar, devolver eco

fn main() -> int {
    let server: int = tcp_listen("0.0.0.0", 9000)
    if server < 0 {
        print("failed to listen on port 9000")
        return 1
    }
    print("echo server listening on :9000")

    // Accept one client for demonstration
    let client: int = tcp_accept(server)
    if client < 0 {
        print("accept failed")
        return 1
    }
    print("client connected")

    // Read a line and echo it back
    let msg: String = tcp_read_line(client)
    print("received: " + msg)
    tcp_write(client, "echo: " + msg + "\n")

    tcp_close(client)
    tcp_close(server)
    print("done")
    return 0
}
Illustrative outputstdout
echo server listening on :9000
client connected
received: hello
done

How it works

tcp_listen("0.0.0.0", port) creates a listening socket on all interfaces. tcp_accept blocks until a client connects and returns a new file descriptor for that connection. The server reads one line, echoes it back prefixed with "echo: ", and closes both sockets.

For a production server, you would wrap the accept in a while loop and spawn a thread per client, or use http_serve_mt which handles the thread pool automatically.