Hello! I'm pretty new to Nim. I'd like to know how to send binary over ws, most of websocket libs accept strings for binary which is confusing for me. I also haven't worked with binary much so i'd like to know how to send a seq or an object over the network. The lib i currently use is websocket.nim. Here's what i want to do:
#...
let data = @[mouse.x, mouse.y] # <== Data i want to send
discard sendBinary(#[...]#)
#...
Server (Node.js):
// ...
ws.on('message', (msg) => {
const data = new Float32Array(msg);
console.log(data[0], data[1]);
});
// ...
Could someone help? I tried to do something but i either get a compiler error or wrong data on the server.
You need to serialize data, one common format is json:
import std/json
let data = @[mouse.x, mouse.y]
let jsonData = %data # Convert seq to JsonNode
discard socket.send($jsonData) # Convert to string and send
ws.on('message', (msg) => {
const data = JSON.parse(msg);
console.log(data[0], data[1]);
});
Also, strings in nim are (almost) equivalent to seq[byte]. So you can do something like
proc toString(bytes: openArray[byte]): string =
if bytes.len > 0:
result = newString(bytes.len)
copyMem(addr result[0], addr bytes[0], bytes.len)
ws.send(yourData.toString)
But maybe your client lib already has an overload like proc send(ws: WSClient, data: openArray[byte]) or similar.
As darkestpigeon mentioned, string in Nim is a byte sequence; you have a valid ASCII text string if the values are between 0-127. Anything 128-255 shows as garbage when printed, but can be easily interpreted as values with ord.
std/unicode has a seq[Rune] for Unicode-encoded strings.
Anything 128-255 shows as garbage when printed, but can be easily interpreted as values with ord.
why? utf-8 is pretty common...
After review, it looks like a string can print a UTF-8 encoded string properly in whole, but you can't print the individual runes without converting them to seq[Rune] first. The sequence of bytes can be printed, but depending on the encoded runes, the interpreted char values of the bytes could be garbage.
Does string printing behavior depend on terminal font and settings?