Sockets, Web & AI

Networking, Web & AI Integrations

TCP & UDP sockets, HTTP web server and client, RFC 6455 WebSockets, streaming LLM integrations, and cosine vector similarity.

Architecture Two-Tier Engine

The Two-Tier Network Stack

BramandScript enforces a clean architectural separation between host operating system primitives and high-level application protocols (Rule 12).

✦ Tier 1: Low-Level Host Primitives (std/net)

Built in Go standard library with zero external dependencies:

  • • Raw TCP Sockets: listen_tcp, dial_tcp, tcp_read_line
  • • Raw UDP Datagrams: listen_udp, send_to, recv_from
  • • Encrypted TLS Sockets: tls_dial with SNI & tls_listen
✦ Tier 2: 100% Pure BramandScript Protocols (.bmd)

Implemented entirely in BramandScript atop Tier 1 sockets:

  • • std/http: RFC 7230 Wire Parser, Server, Client, Router
  • • std/ws: RFC 6455 Handshake, Frame Codec, Client/Server
  • • std/dns: RFC 1035 UDP Codec, 0xC0 Compression, Cache
  • • std/https: Pure BMD HTTPS Client & Server over TLS
Tier 1 Primitives

Raw TCP & UDP Sockets (std/net)

Low-level networking primitives built directly on the Go standard library (net). Provides full duplex streaming TCP connections with line-by-line buffering, idle timeouts, and high-throughput UDP packet sockets.

bramand — Raw TCP and UDP Socket Communication
import "std/net" as net;

// 1. Raw TCP Server
let srv = net.create_server(fn(sock) {
    sock.set_timeout(5000);
    let line = sock.read_line();
    if (line != null) {
        sock.write("ECHO: " + trim(line) + "\n");
    }
    sock.close();
});
srv.listen(8080);

// 2. Raw TCP Client
let client = net.connect("127.0.0.1", 8080);
client.write("Hello BramandNet\n");
let ack = client.read_line();
println(trim(ack)); // "ECHO: Hello BramandNet"
client.close();
srv.close();

// 3. Raw UDP Datagrams
let udp_srv = net.create_udp_socket(9090);
let udp_cli = net.create_udp_socket();
udp_cli.send_to("FAST_DATAGRAM", "127.0.0.1:9090");

let pkt = udp_srv.recv_from(4096);
println("Received:", pkt["data"], "from", pkt["addr"]);
udp_srv.close();
udp_cli.close();
Pure BramandScript

Pure BramandScript HTTP/1.1 Engine (std/http)

A 100% self-hosted RFC 7230 HTTP/1.1 protocol engine written entirely in BramandScript on top of raw TCP sockets. Includes a strict wire protocol parser (std/http/parser), high-performance HTTP server (http.create_server), flexible HTTP client (http.get, http.post, http.put, http.delete_req), and native Trie Router integration.

bramand — Pure BMD HTTP Server, Client & Router
import "std/http" as http;

// 1. Initialize Radix-Trie Router
let router = http.create_router();

router.get("/api/users", fn(req, res) {
    res.json([{ "id": 1, "name": "Aryabhata" }]);
});

router.post("/api/users", fn(req, res) {
    let body = req.json();
    res.status(201).json({ "created": body, "id": 2 });
});

router.get("/api/users/:id", fn(req, res) {
    let uid = req.params["id"];
    res.json({ "user_id": uid, "found": true });
});

// 2. Start HTTP Server with Router
let server = http.create_server(router);
server.listen(8080);

// 3. Pure BMD HTTP Client Requests
let res1 = http.get("http://127.0.0.1:8080/api/users");
println("GET Status:", res1["status"], "Body:", res1.json());

let res2 = http.post("http://127.0.0.1:8080/api/users", { "name": "Varahamihira" });
println("POST Status:", res2["status"]);

let res3 = http.delete_req("http://127.0.0.1:8080/api/users/2");
server.close();

HTTP Client Reference Table

FunctionSignatureReturnDescription
http.gethttp.get(url, [opts])HASHSends HTTP GET request; returns response hash with status, headers, body, json(), text().
http.posthttp.post(url, body, [opts])HASHSends HTTP POST request; automatically serializes map/array body to JSON.
http.puthttp.put(url, body, [opts])HASHSends HTTP PUT request with payload and optional headers.
http.delete_reqhttp.delete_req(url, [opts])HASHSends HTTP DELETE request to target endpoint.
http.requesthttp.request(options)HASHExecutes customized request with {"method", "url", "body", "headers", "timeout"}.
RFC 6455 Pure BMD

Pure BramandScript RFC 6455 WebSocket Engine (std/ws)

A 100% self-hosted RFC 6455 WebSocket protocol engine implemented entirely in pure BramandScript atop raw TCP sockets. Features official SHA-1/Base64 accept key derivation, binary frame encoding with FIN and opcode bitfields, client XOR 4-byte payload masking, 7-bit/16-bit/64-bit payload lengths, ping/pong heartbeats, and room broadcasting.

bramand — Realtime WebSocket Server & Client
import "std/ws" as ws;

// 1. Start WebSocket Server
let server = ws.create_server(8081, fn(conn) {
    conn.on("message", fn(msg) {
        conn.send("ACK:" + msg);
        server.broadcast("ANNOUNCE: New message received");
    });
});

// 2. Connect WebSocket Client
let client = ws.connect("ws://127.0.0.1:8081/chat", fn(c) {
    c.send("Hello WebSocket");
});

client.on("message", fn(reply) {
    println("Client received:", reply);
    client.close(1000, "Done");
    server.close();
});
RFC 1035 Pure BMD

Pure BramandScript UDP DNS Resolver (std/dns)

A 100% self-hosted RFC 1035 UDP DNS packet codec and resolver engine. Directly formats binary queries, parses 12-byte headers, resolves QNAME labels with 0xC0 compression pointers, and manages an in-memory TTL cache.

bramand — RFC 1035 DNS Resolver & In-Memory Cache
import "std/dns" as dns;

// 1. Direct Resolution with In-Memory TTL Cache
let ips = dns.resolve("bramand.org", dns.TYPE_A, "8.8.8.8:53");
println("Resolved A records:", ips);

// 2. Convenience Single-IP Lookup
let ip = dns.lookup("bramand.org");
println("Primary IP:", ip);

// 3. Low-Level Packet Codec
let query_pkt = dns.encode_query("example.com", dns.TYPE_A, 0x1234);
let parsed = dns.decode_response(query_pkt);
println("Decoded Question:", parsed["questions"][0]["name"]);
Pure BMD HTTPS

Pure BramandScript HTTPS Client & Server (std/https)

Combines raw TLS dialer sockets (tls_dial) with the pure BMD HTTP wire parser and client pipeline. Enforces Server Name Indication (SNI) verification and TLS certificate validation by default.

bramand — Secure HTTPS Request & Server
import "std/https" as https;

// 1. Secure HTTPS GET
let res = https.get("https://api.github.com/zen", {
    "headers": { "User-Agent": "BramandScript/1.0" }
});
println("HTTPS Status:", res["status"], "Zen:", res.text());

// 2. Secure HTTPS POST with JSON
let post_res = https.post("https://httpbin.org/post", { "auth": "secure_token" });
println("POST Response:", post_res.json());
AI Integration

AI Integrations: LLM Streaming & Structured Outputs

First-class primitives for connecting to modern AI Large Language Models (Ollama, OpenAI, Gemini, Anthropic, and local vLLM/llama.cpp inference nodes). Features realtime token streaming using Server-Sent Events (SSE) and schema-validated structured JSON output generation.

bramand — LLM Streaming and Structured JSON
// 1. Direct LLM Prompt (defaults to local Ollama http://localhost:11434)
let reply = ai_prompt("llama3", "Explain quantum computing in one sentence")
println(reply)

// 2. Realtime Token Streaming via Server-Sent Events
ai_stream({
    "url": "http://localhost:11434/api/generate",
    "body": {"model": "llama3", "prompt": "Write a haiku", "stream": true}
}, fn(token) {
    print_raw(token)  // Streams live tokens directly to console
})

// 3. Structured JSON Output Enforcement
let schema = {"sentiment": "positive|negative|neutral", "score": 0.0}
let parsed = ai_structured({
    "model": "llama3",
    "prompt": "Analyze: 'I love BramandScript!'"
}, schema)
println("Sentiment:", parsed["sentiment"], "Score:", parsed["score"])