Nyx provee primitivas TCP incorporadas: tcp_connect, tcp_write, tcp_read, tcp_read_line, y tcp_close. Este ejemplo se conecta a un servidor web y envía manualmente una solicitud HTTP/1.0 sobre un socket TCP crudo.
46-tcp-client.nxFuente →
// TCP client — connect, send a request, read a response // Cliente TCP — conectar, enviar una solicitud, leer una respuesta fn main() -> int { // Connect to a TCP server let fd: int = tcp_connect("example.com", 80) if fd < 0 { print("connection failed") return 1 } // Send an HTTP request manually over TCP let req: String = "GET / HTTP/1.0\r\nHost: example.com\r\n\r\n" tcp_write(fd, req) // Read the response line by line let status_line: String = tcp_read_line(fd) print("status: " + status_line) // Read headers until empty line var line: String = tcp_read_line(fd) while line.length() > 0 and line != "\r" { line = tcp_read_line(fd) } // Read body let body: String = tcp_read(fd, 256) print("body (first 256 bytes): " + body.substring(0, 100)) tcp_close(fd) return 0 }
Salida ilustrativastdout
status: HTTP/1.0 200 OK body (first 256 bytes): <!doctype html>...
Cómo funciona
tcp_connect(host, port) resuelve el nombre de host y crea una conexión TCP, devolviendo un descriptor de archivo. tcp_write envía datos, tcp_read_line lee hasta encontrar \n, y tcp_read(fd, n) lee hasta n bytes. Cierra siempre las conexiones con tcp_close.
Este es el nivel más bajo de redes en Nyx. Para HTTP, usa std/http, que envuelve estas primitivas con el parseo de solicitud/respuesta (ver receta 49).