A two way connection that stays open between browser and server, with rooms for broadcasting.
import net.websocket
A WebSocket is a connection that starts as one HTTP request and then stays open, and either side sends a message whenever it likes: live chat, notifications, dashboards, games. This package has both ends. The server takes connections with Listen and Accept on its own port, and a client connects with Dial; AcceptWSS and DialWSS do the same over TLS. It runs its own listener and does not plug into the net.http server. For the Socket.IO protocol that many JavaScript apps use (events, acknowledgements, reconnection) use net.socketio instead; a plain browser WebSocket talks to this package directly.
Core ideas:
•
Receive blocks until a whole message has arrived and returns a Message; check its kind with IsText, IsBinary and IsClose. Pings are answered for you. Poll waits at most a given time.
•
A Hub groups connections into rooms so one call sends to every member.
•
One connection is read by one thread. To serve many clients, give each connection its own thread.
Things that catch people out:
•
A Hub has no lock. When several connection threads share it, wrap Register, Unregister and Broadcast in a sync mutex.
•
Keep a copy of the connection for Unregister. When the other side closes, Receive clears conn.fd, and Unregister matches on that socket number, so unregistering with the closed connection removes nothing. Register a copy taken right after Accept and unregister with the same copy.
•
Text stops at a zero byte and is not checked as UTF-8. Send binary data as binary and read it from m.data and m.len; that buffer belongs to the connection and is reused by the next binary message, so copy what you keep.
•
The server takes any origin and offers no subprotocols or compression; check conn.hdr yourself if you need an Origin rule. A frame larger than 100 MB closes the connection.
Each example below runs a server and its clients in the same program, the server in a thread started with spawn, on a free port chosen by Listen(0). That keeps them runnable offline; in a real program the clients are browsers using the JavaScript WebSocket API, which speaks the same protocol.
Typed JSON messages
A WebSocket carries text or bytes; the structure is up to you. The common choice is one JSON object per message with a type field, and a server loop that reads a message, looks at the type and answers. Receive waits for the next message, IsText tells text from close or binary frames, and json.Str quotes user text safely when you build a reply by hand.
joined users: 1
Sara said: salam "everyone"
{"type": "error", "reason": "unknown type"}
Always answer an unknown type with an error message instead of closing; clients built later may send types an older server does not know.
Rooms with a Hub
A chat or a live score page sends one message to many connections. A Hub keeps connections by room name: Register adds a connection to a room, Broadcast sends text to every member and returns how many got it, and RoomSize counts the members. A natural room name is the path the client connected to, which the server sees in conn.path.
net-websocket-rooms.salam
import net.websocket
importstrmut server := websocket.Server {}
mut hub := websocket.NewHub()
funcacceptor():
repeat3:
conn := websocket.Accept(server)
room := str.Replace(conn.path, "/rooms/", "")
websocket.Register(hub, room, conn)
endendfuncmain:
server = websocket.Listen(0)
port := websocket.Port(server)
t := spawn(acceptor)
mut ali := websocket.Dial("127.0.0.1", port, "/rooms/news")
mut sara := websocket.Dial("127.0.0.1", port, "/rooms/news")
mut reza := websocket.Dial("127.0.0.1", port, "/rooms/sport")
join(t)
println"news:", websocket.RoomSize(hub, "news"), "sport:", websocket.RoomSize(hub, "sport")
println"sent to", websocket.Broadcast(hub, "news", "rates are up"), "in news"println"sent to", websocket.Broadcast(hub, "sport", "2 to 1 at half time"), "in sport"println"ali:", websocket.ReceiveText(ali)
println"sara:", websocket.ReceiveText(sara)
println"reza:", websocket.ReceiveText(reza)
println"nobody in chess:", websocket.Broadcast(hub, "chess", "hello")
websocket.Close(ali)
websocket.Close(sara)
websocket.Close(reza)
websocket.CloseServer(server)
end
Output
news: 2 sport: 1
sent to 2 in news
sent to 1 in sport
ali: rates are up
sara: rates are up
reza: 2 to 1 at half time
nobody in chess: 0
In a real server, read each connection in its own thread and call Unregister when it closes, so broadcasts do not go to connections that are gone. The next section shows that server.
A chat server with a thread per connection
Here every member thread accepts one connection, registers it in the lobby room, and then reads that connection until it closes, broadcasting each line to the room. Several threads may call Accept on the same server; each gets a different client. The hub is shared, so every hub call is wrapped in one mutex. The thread registers entry, a copy taken before any Receive, and unregisters with that same copy; with conn itself the room would still count two members at the end.
net-websocket-chat-server.salam
import net.websocket
importstrimport sync
mut server := websocket.Server {}
mut hub := websocket.NewHub()
mut lock := sync.NewMutex()
funcannounce(text: str):
sync.Lock(lock)
_ := websocket.Broadcast(hub, "lobby", text)
sync.Unlock(lock)
endfuncmember():
mut conn := websocket.Accept(server)
ifnot websocket.IsOpen(conn): retend
name := str.Replace(conn.path, "/chat/", "")
entry := conn
sync.Lock(lock)
websocket.Register(hub, "lobby", entry)
sync.Unlock(lock)
_ := websocket.SendText(conn, "welcome, " + name)
until websocket.IsOpen(conn):
m := websocket.Receive(conn)
ifnot websocket.IsText(m): breakendannounce(name + ": " + m.text)
end
sync.Lock(lock)
websocket.Unregister(hub, "lobby", entry)
sync.Unlock(lock)
announce(name + " left")
websocket.Close(conn)
endfuncmain:
server = websocket.Listen(0)
port := websocket.Port(server)
a := spawn(member)
b := spawn(member)
mut sara := websocket.Dial("127.0.0.1", port, "/chat/sara")
println"sara got:", websocket.ReceiveText(sara)
mut reza := websocket.Dial("127.0.0.1", port, "/chat/reza")
println"reza got:", websocket.ReceiveText(reza)
_ := websocket.SendText(sara, "lunch at one?")
println"sara got:", websocket.ReceiveText(sara)
println"reza got:", websocket.ReceiveText(reza)
websocket.Close(reza)
println"sara got:", websocket.ReceiveText(sara)
websocket.Close(sara)
join(a)
join(b)
println"left in the lobby:", websocket.RoomSize(hub, "lobby")
websocket.CloseServer(server)
sync.Destroy(lock)
end
Output
sara got: welcome, sara
reza got: welcome, reza
sara got: sara: lunch at one?
reza got: sara: lunch at one?
sara got: reza left
left in the lobby: 0
A thread per client is fine for hundreds of connections. Start one member thread per expected client, or have each thread spawn the next one after its Accept returns, so there is always one waiting for the next visitor.
Checking a token during the handshake
A WebSocket starts as an HTTP request, and its headers are kept in conn.hdr, so the server can check a token before it trusts the connection; read it with http.HeaderValue from net.http. On the client side DialWith adds extra header lines. A connection without a valid token gets a short message and is closed, which the client sees as a close message from Poll.
net-websocket-auth.salam
import net.websocket
import net.http
mut server := websocket.Server {}
funcgate():
repeat2:
mut conn := websocket.Accept(server)
token := http.HeaderValue(conn.hdr, "authorization")
if token == "Bearer sara-token":
_ := websocket.SendText(conn, "welcome, sara")
question := websocket.ReceiveText(conn)
_ := websocket.SendText(conn, "you asked: " + question)
else:
_ := websocket.SendText(conn, "who are you?")
end
websocket.Close(conn)
endendfuncattempt(port: int, extra: str):
mut c := websocket.DialWith("127.0.0.1", port, "/live", extra)
println"open:", websocket.IsOpen(c), "server says:", websocket.ReceiveText(c)
if extra != "":
_ := websocket.SendText(c, "any news?")
println websocket.ReceiveText(c)
end
m := websocket.Poll(c, 2000)
println"closed by the server:", websocket.IsClose(m)
endfuncmain:
server = websocket.Listen(0)
t := spawn(gate)
attempt(websocket.Port(server), "Authorization: Bearer sara-token\r\n")
attempt(websocket.Port(server), "")
join(t)
websocket.CloseServer(server)
end
Output
open: true server says: welcome, sara
you asked: any news?
closed by the server: true
open: true server says: who are you?
closed by the server: true
Browsers cannot set an Authorization header on a WebSocket. For browser clients put a short lived token in the URL, such as /live?token=..., and check conn.path instead.
Waiting without blocking: Poll and ping
A client that waits a long time for an answer should know the connection is still alive, and proxies close connections that stay silent. Poll(conn, ms) waits at most that many milliseconds and returns a message of kind TIMEOUT when nothing arrived, which is the moment to send a Ping. The loop below waits for a job report, pinging every 100 ms, and gives up after 50 quiet rounds.
net-websocket-heartbeat.salam
import net.websocket
import time
mut server := websocket.Server {}
funcworker():
mut conn := websocket.Accept(server)
time.Sleep(400)
_ := websocket.SendText(conn, "report ready")
until websocket.IsOpen(conn):
m := websocket.Receive(conn)
if websocket.IsClose(m) or m.kind == websocket.NONE: breakendend
websocket.Close(conn)
endfuncmain:
server = websocket.Listen(0)
t := spawn(worker)
mut c := websocket.Dial("127.0.0.1", websocket.Port(server), "/jobs/42")
mut idle := 0mut answer := ""until answer == ""and idle < 50:
m := websocket.Poll(c, 100)
if m.kind == websocket.TIMEOUT:
idle++
_ := websocket.Ping(c, "still here")
else websocket.IsText(m):
answer = m.text
else websocket.IsClose(m):
breakendendprintln"answer:", answer
println"pinged while waiting:", idle > 0
websocket.Close(c)
join(t)
websocket.CloseServer(server)
end
Output
answer: report ready
pinged while waiting: true
The send functions return 0 on success and a negative number when the connection is gone, so check the result of SendText and Ping in long running loops.
Which function for which job
Job
Server
Client
Open
Listen, Accept (TLS: LoadWSSConfig, AcceptWSS)
Dial, DialWith (TLS: DialWSS)
Send
SendText, SendBinary, Ping
Receive
Receive (waits), Poll (with a time limit), ReceiveText (text only)
Waits for the next client and completes the WebSocket handshake. If the request is not a valid WebSocket upgrade the connection comes back closed, so check IsOpen.
Takes the next whole message, waiting as long as it takes. It answers pings by itself and joins fragmented messages; on a close it answers and closes the connection.
Sends a close frame if the connection is open and shuts the socket down without freeing the connection, so another thread blocked in Receive on it wakes up. Call Close afterwards to free it.