Nyx by Example

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.

Code

// TCP echo server — listen, accept, echo back

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")

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

    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
}

Output

echo server listening on :9000
client connected
received: hello
done

Explanation

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.

← Previous Next →

Source: examples/by-example/47-tcp-server.nx