nyx-kv basic client
The nyx-kv server speaks RESP protocol on port 6380. This recipe shows how to build a basic client that connects, issues SET/GET/DEL commands, and reads the replies.
Code
// nyx-kv client -- basic SET/GET/DEL operations
// Build a RESP array command from string parts
fn resp_cmd(parts: Array) -> String {
var sb: StringBuilder = StringBuilder.new()
sb.append("*")
sb.append(int_to_string(parts.length()))
sb.append("\r\n")
var i: int = 0
while i < parts.length() {
let p: String = parts[i]
sb.append("$")
sb.append(int_to_string(p.length()))
sb.append("\r\n")
sb.append(p)
sb.append("\r\n")
i = i + 1
}
return sb.to_string()
}
fn main() -> int {
// Connect to nyx-kv on default port 6380
let fd: int = tcp_connect("127.0.0.1", 6380)
if fd < 0 {
print("connection failed (is nyx-kv running?)")
return 1
}
// SET name "Nyx"
tcp_write(fd, resp_cmd(["SET", "name", "Nyx"]))
let set_reply: String = tcp_read_line(fd)
print("SET -> " + set_reply.trim())
// GET name
tcp_write(fd, resp_cmd(["GET", "name"]))
let hdr: String = tcp_read_line(fd)
let val: String = tcp_read_line(fd)
print("GET name -> " + val.trim())
// DEL name
tcp_write(fd, resp_cmd(["DEL", "name"]))
let del_reply: String = tcp_read_line(fd)
print("DEL -> " + del_reply.trim())
tcp_close(fd)
return 0
}
Output
SET -> +OK GET name -> Nyx DEL -> :1
Explanation
RESP (REdis Serialization Protocol) encodes each command as an array of bulk strings: *N\r\n announces an N-element array, then each element is $len\r\n<data>\r\n. The helper resp_cmd builds this wire format with a StringBuilder, avoiding costly string concatenations.
Replies come in four flavors: simple strings (+OK), errors (-ERR), integers (:1), and bulk strings ($3\r\nNyx\r\n). For GET we read two lines: the length header and the value. For SET and DEL we just read one line. The server maintains state across a single TCP connection, so keep the socket open while issuing commands.
Because nyx-kv is Redis-compatible, you can also test it with redis-cli -p 6380 — the same RESP bytes go over the wire.