Cliente TCP
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.
Código
// 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
}
Salida
status: HTTP/1.0 200 OK body (first 256 bytes): <!doctype html>...
Explicación
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. Siempre cierre las conexiones con tcp_close.
Este es el nivel más bajo de redes en Nyx. Para HTTP, use std/http, que envuelve estas primitivas con el parseo de solicitud/respuesta (ver receta 49).