Networking, Web & AI Integrations
TCP & UDP sockets, HTTP web server and client, RFC 6455 WebSockets, streaming LLM integrations, and cosine vector similarity.
The Two-Tier Network Stack
BramandScript enforces a clean architectural separation between host operating system primitives and high-level application protocols (Rule 12).
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_dialwith SNI &tls_listen
.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
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.
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 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.
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
| Function | Signature | Return | Description |
|---|---|---|---|
http.get | http.get(url, [opts]) | HASH | Sends HTTP GET request; returns response hash with status, headers, body, json(), text(). |
http.post | http.post(url, body, [opts]) | HASH | Sends HTTP POST request; automatically serializes map/array body to JSON. |
http.put | http.put(url, body, [opts]) | HASH | Sends HTTP PUT request with payload and optional headers. |
http.delete_req | http.delete_req(url, [opts]) | HASH | Sends HTTP DELETE request to target endpoint. |
http.request | http.request(options) | HASH | Executes customized request with {"method", "url", "body", "headers", "timeout"}. |
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.
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();
});
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.
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 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.
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 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.
// 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"])
Vector Similarity & AI Embeddings Search
High-dimensional vector distance metrics and nearest-neighbor search for AI retrieval-augmented generation (RAG) and embedding comparisons.
// Distance & Similarity Metrics
let v1 = vec([1.0, 0.0, 0.5])
let v2 = vec([0.8, 0.2, 0.4])
println("Cosine Similarity:", cosine_similarity(v1, v2))
println("Cosine Distance: ", cosine_distance(v1, v2))
println("Euclidean Distance:", euclidean_distance(v1, v2))
// Vector Database Search (RAG)
let query = vec([0.9, 0.1, 0.0])
let corpus = [
{"id": "doc_1", "title": "Compiler Architecture", "embedding": vec([0.88, 0.12, 0.01])},
{"id": "doc_2", "title": "Gardening Handbook", "embedding": vec([0.05, 0.85, 0.52])},
{"id": "doc_3", "title": "Bytecode Virtual Machine", "embedding": vec([0.92, 0.08, 0.02])}
]
let matches = vector_search(query, corpus, 2, "cosine")
println("Top Match:", matches[0]["item"]["title"], "Score:", matches[0]["score"])
Persistent In-Memory Spatial Vector Index (std/ai) & RAG Pipeline
The std/ai module provides a fast K-Nearest Neighbors (KNN) spatial index supporting vector insertion, similarity search, serialization to JSON files, and sliding-window document chunking:
import "std/ai" as ai;
// 1. Semantic Document Chunking
let doc = "BramandScript Bytecode VM executes 64-bit opcodes on a dynamic stack. Pure Go stdlib zero dependencies.";
let chunks = ai.chunk_text(doc, { "chunk_size": 40, "chunk_overlap": 10 });
// 2. Initialize In-Memory KNN Spatial Vector Index
let idx = ai.new_index("cosine");
idx.add("doc_sec_01", [0.95, 0.12, 0.05], { "text": chunks[0]["text"] });
idx.add("doc_sec_02", [0.10, 0.89, 0.22], { "text": chunks[1]["text"] });
// 3. Nearest Neighbor Similarity Search
let hits = idx.search([0.92, 0.15, 0.03], 1);
println("Top Hit ID:", hits[0]["id"], "Score:", hits[0]["score"]);
// 4. Format RAG Prompt Context Block for LLM
let rag_context = ai.build_rag_context([0.92, 0.15, 0.03], idx, 2);
println("RAG Context:\n", rag_context);