Nyx by Example

TCP Client

Nyx provides built-in TCP primitives: tcp_connect, tcp_write, tcp_read, tcp_read_line, and tcp_close. This example connects to a web server and manually sends an HTTP/1.0 request over a raw TCP socket.

Code

// TCP client — connect, send a request, read a response

fn main() -> int {
    let fd: int = tcp_connect("example.com", 80)
    if fd < 0 {
        print("connection failed")
        return 1
    }

    let req: String = "GET / HTTP/1.0\r\nHost: example.com\r\n\r\n"
    tcp_write(fd, req)

    let status_line: String = tcp_read_line(fd)
    print("status: " + status_line)

    var line: String = tcp_read_line(fd)
    while line.length() > 0 and line != "\r" {
        line = tcp_read_line(fd)
    }

    let body: String = tcp_read(fd, 256)
    print("body (first 256 bytes): " + body.substring(0, 100))

    tcp_close(fd)
    return 0
}

Output

status: HTTP/1.0 200 OK
body (first 256 bytes): <!doctype html>...

Explanation

tcp_connect(host, port) resolves the hostname and creates a TCP connection, returning a file descriptor. tcp_write sends data, tcp_read_line reads until \n, and tcp_read(fd, n) reads up to n bytes. Always close connections with tcp_close.

This is the lowest level of networking in Nyx. For HTTP, use std/http which wraps these primitives with request/response parsing (see recipe 49).

← Previous Next →

Source: examples/by-example/46-tcp-client.nx