A Socket.IO client: events, acknowledgements, namespaces and automatic reconnection.
import net.socketio
Socket.IO is the usual live messaging library in the Node.js world. This package is a client for Socket.IO 3 and 4 servers (Engine.IO protocol 4), over WebSocket or HTTP long polling; it has no server of its own. Use it when the other side already speaks Socket.IO, for example a Node.js chat or dashboard backend. When you control both ends and the client is a browser, a plain net.websocket server is simpler, because Socket.IO adds its own packet format on top of the WebSocket.
The model: Dial connects, On sets a listener for an event and the Emit... functions send events. Nothing is read in the background: listeners run only while the program processes messages with Run, RunFor, Pump, Next or EmitAck. The arguments of every event are a JSON array, read with ArgStr, ArgInt and the like. If the sender wants an answer, the event's ack_id is not negative and you answer it with Reply. For several namespaces on one connection, create a Manager.
Things that catch people out:
•
A program that never pumps never hears anything. Pings from the server are answered while you pump, so a client that sleeps for longer than the server's ping timeout is disconnected.
•
Next returns connection events too, such as EV_CONNECT; loop until the kind you stop on, not until the first event that is not EV_EVENT. Its queue starts with the first Next call and keeps the newest event_queue events (256 by default), dropping the oldest.
•
Free what you build.ArgsFree for argument lists and AckFree for answers, or a long running client keeps growing.
•
Socket.IO 2 servers (from before 2020) speak an older protocol and are not supported.
Handling events in your own loop
Listeners with On are the usual style, but sometimes a plain loop reads better: a worker that handles one event at a time, or a program that must also do other work between messages. Next waits up to the given milliseconds and returns one Event. Its kind says what it is: a message from the server (EV_EVENT, with the name and the arguments), a change of the connection such as EV_DISCONNECT (the reason is in message), or EV_TIMEOUT when nothing came.
net-socketio-next-loop.salam
import net.socketio
import net.websocket
mut server := websocket.Server {}
funcfake_server():
mut conn := websocket.Accept(server)
_ := websocket.SendText(
conn, `0{"sid":"s1","upgrades":[],"pingInterval":20000,"pingTimeout":5000}`
)
m := websocket.Poll(conn, 3000)
if m.kind == websocket.TEXT and m.text == "40":
_ := websocket.SendText(conn, `40{"sid":"a1"}`)
_ := websocket.SendText(conn, `42["price","BTC",61250]`)
_ := websocket.SendText(conn, `42["price","ETH",2410]`)
_ := websocket.SendText(conn, `42["halt","maintenance"]`)
_ := websocket.SendText(conn, "41")
end
_ := websocket.Poll(conn, 1000)
websocket.Close(conn)
endfuncmain:
server = websocket.Listen(0)
t := spawn(fake_server)
mut o := socketio.NewOptions()
o.transports = socketio.TRANSPORT_WEBSOCKET
o.reconnection = false
c := socketio.DialWith("http://127.0.0.1:" + websocket.Port(server), o)
mut going := trueuntil going:
e := socketio.Next(c, 3000)
if e.kind == socketio.EV_EVENT and e.name == "price":
println"price", socketio.ArgStr(e, 0), socketio.ArgInt(e, 1)
else e.kind == socketio.EV_EVENT:
println"event", e.name, socketio.ArgStr(e, 0)
else e.kind == socketio.EV_DISCONNECT:
println"disconnected:", e.message, e.message == socketio.REASON_SERVER_DISCONNECT
going = falseelse e.kind == socketio.EV_TIMEOUT:
println"nothing arrived in time"
going = falseendend
socketio.Close(c)
join(t)
websocket.CloseServer(server)
end
Output
price BTC 61250
price ETH 2410
event halt maintenance
disconnected: io server disconnect true
The program brings its own tiny server, which speaks the Socket.IO wire format over a WebSocket, so it runs without Node.js. A real server sends the same packets: 42["price","BTC",61250] is an event named price with two arguments, and 41 is the server closing the namespace, which arrives as REASON_SERVER_DISCONNECT. After that reason the client does not reconnect by itself, because the server meant it.
Logging in with a token
Socket.IO servers usually check the user in a middleware that reads the auth object of the connection. Put that JSON in Options.auth before dialling. When the middleware says no, the server answers with a connect error instead of a session; Refused is then true and RefusalReason holds the message the server gave.
net-socketio-auth.salam
import net.socketio
funcmain:
mut o := socketio.NewOptions()
o.auth = `{"token":"eyJhbGciOiJIUzI1NiJ9.e30.x"}`
o.reconnection = false
c := socketio.DialWith("https://chat.example.com", o)
if socketio.Refused(c):
println"the server refused us:", socketio.RefusalReason(c)
ret1endifnot socketio.IsConnected(c):
println"could not connect:", socketio.LastError(c)
ret1endprintln"connected as", socketio.Id(c), "over", socketio.TransportName(c)
socketio.Close(c)
ret0end
This needs a running server, so it is only checked here. With a Node.js server, the matching check is an io.use((socket, next) => ...) that reads socket.handshake.auth.token and calls next(new Error("...")) to refuse.
Acknowledgements in both directions
An acknowledgement is Socket.IO's request and reply: the sender numbers an event and the other side answers that number. EmitAck sends an event and waits, up to the time you give, for the server's answer; ok is false when it did not come in time. The other way round, when the server sends an event with an id, e.ack_id holds it and Reply, ReplyStr or ReplyJSON answers it. The fake server below shows both packets on the wire: 420[...] is the client's event with ack id 0 and 4317["yes"] is the client's answer to the server's ack id 17.
net-socketio-ack.salam
import net.socketio
import net.websocket
import encoding.json
mut server := websocket.Server {}
mut seen := Vector {} asVector<str>
funcfake_server():
mut conn := websocket.Accept(server)
_ := websocket.SendText(
conn, `0{"sid":"s1","upgrades":[],"pingInterval":20000,"pingTimeout":5000}`
)
if websocket.ReceiveText(conn) != "40": retend
_ := websocket.SendText(conn, `40{"sid":"a1"}`)
join := websocket.ReceiveText(conn)
seen.Push(join)
_ := websocket.SendText(conn, `430[{"ok":true,"members":3}]`)
_ := websocket.SendText(conn, `4217["confirm","order 1042"]`)
seen.Push(websocket.ReceiveText(conn))
_ := websocket.SendText(conn, "41")
_ := websocket.Poll(conn, 1000)
websocket.Close(conn)
endfuncmain:
server = websocket.Listen(0)
t := spawn(fake_server)
mut o := socketio.NewOptions()
o.transports = socketio.TRANSPORT_WEBSOCKET
o.reconnection = false
c := socketio.DialWith("http://127.0.0.1:" + websocket.Port(server), o)
mut a := socketio.NewArgs()
socketio.AddStr(a, "room-1")
mut answer := socketio.EmitAck(c, "join", a, 2000)
socketio.ArgsFree(a)
println"join answered:",
answer.ok,
"members:",
json.GetInt(socketio.AckArg(answer, 0), "members")
socketio.AckFree(answer)
mut going := trueuntil going:
e := socketio.Next(c, 3000)
if e.kind == socketio.EV_EVENT and e.name == "confirm":
println"server asks:", socketio.ArgStr(e, 0), "ack id", e.ack_id
_ := socketio.ReplyStr(e, "yes")
else e.kind == socketio.EV_DISCONNECT or e.kind == socketio.EV_TIMEOUT:
going = falseendend
socketio.Close(c)
join(t)
websocket.CloseServer(server)
println"the server saw:"each line in seen: println" ", line endend
Output
join answered: true members: 3
server asks: order 1042 ack id 17
the server saw:
420["join","room-1"]
4317["yes"]
Answer each acknowledged event once. Servers usually put a timeout on their own emitWithAck, so reply before you start slow work, or reply with a "started" status and send the result as a separate event.
A bot that stays connected
A long running client joins a room, answers some messages and survives network trouble. EmitAck sends an event and waits for the server's answer, which is how you know the join worked. Run then handles events until the client is closed, and reconnects on its own after a dropped connection, waiting reconnection_delay milliseconds and longer each time up to reconnection_delay_max. The disconnect and reconnect listeners let you log both.
net-socketio-chat-bot.salam
import net.socketio
importstrmut client := socketio.Client {}
funcmain:
mut o := socketio.NewOptions()
o.reconnection_attempts = 10
o.reconnection_delay = 2000
client = socketio.DialWith("http://localhost:3000", o)
ifnot socketio.IsConnected(client):
println"cannot reach the chat:", socketio.LastError(client)
ret1endmut a := socketio.NewArgs()
socketio.AddStr(a, "support")
mut k := socketio.EmitAck(client, "join", a, 5000)
socketio.ArgsFree(a)
ifnot k.ok:
println"joining the room timed out"ret1endprintln"joined support, members:", socketio.AckInt(k, 0)
socketio.AckFree(k)
socketio.On(client, "message", (e: socketio.Event): text := socketio.ArgStr(e, 1) ifstr.StartsWith(text, "!time"): _ := socketio.EmitStr(client, "message", "office hours are 9 to 17") endend)
socketio.On(client, "disconnect", (e: socketio.Event): println"lost the connection:", e.message end)
socketio.On(client, "reconnect", (e: socketio.Event): _ := e println"back after", socketio.Attempts(client), "attempts"end)
socketio.Run(client)
ret0end
A bot that only reacts to events can stay in Run for its whole life; it returns when Close is called or when reconnection gives up.
Which way to receive
Situation
Use
The program only reacts to events
On listeners and Run
A test or a script that runs for a while and stops
RunFor
Your own main loop, with other work between events
Pump with a short timeout, once per turn of the loop
Socket.IO runs on a layer called Engine.IO. Every message on that layer starts with a digit that gives its kind: open, close, ping, pong, message, upgrade and noop. Socket.IO packets travel inside messages of the "message" kind.
The kinds of Socket.IO packet: connecting to a namespace, disconnecting, an event, an acknowledgement, a connect error, and the binary event and binary acknowledgement whose bytes follow the packet separately.
The value of the kind field in the event that Next returns. A message event is one of the server's messages; the rest report on the connection itself: connecting and disconnecting, errors, reconnection attempts, pings, timeouts and the upgrade to WebSocket. Listeners are called with the English names of these events, such as connect and disconnect.
The text in the message field of a disconnect event, telling why the connection ended: the server or the program itself closed it, a ping did not arrive in time, the transport closed or failed, or a packet could not be read.
The next event from the queue, or an event of kind EV_TIMEOUT if nothing arrived within the timeout; a negative timeout waits forever. Listeners are called too. The queue starts with the first call.
Sends an event and waits until the acknowledgement arrives or the timeout runs out; 0 uses ack_timeout, a negative value waits forever. Other events that arrive meanwhile go to the listeners.