Unlimitedws is a tiny, well-tested library which helps you build a robust Websocket server with a few lines of code. Specifically, the Websocket server can handle up to several million concurrent connections with only a few GBs of memory. The library has successfully done that by utilizing async IO, careful tuning OS, zero-upgrade TCP connections, efficient buffer reuse and worker pool in case of DDOS.
- Linux OS
- Some MBs of memory :)
go get github.com/hxt365/unlimitedws
A robust Echo Websocket system, that handles 100k concurrent connections within only 200 MBs of memory, can be implemented as follows:
server, _ := unlimitedws.DefaultServer(":8000")
// OnConnect handles logic when a connection comes up
server.OnConnect = func(conn net.Conn) {
fmt.Println("welcome", nameConn(conn))
}
// OnRead handles logic when a connection sends a message
server.OnRead = func(conn net.Conn) error {
msg, op, err := wsutil.ReadClientData(conn)
if err != nil {
return err
}
err = wsutil.WriteServerMessage(conn, op, msg)
if err != nil {
return err
}
fmt.Println(string(msg))
return nil
}
// OnClose handles logic when a connection gets closed
server.OnClose = func(conn net.Conn) {
fmt.Println("goodbye", nameConn(conn))
}
server.Run()
Full example: Echo.
Unlimitedws is built on top of the excellent Gobwas library. It is highly recommended to read the documentation of that library for advanced usage.
- Custom Cookie handler, for authentication purpose.
- Close orphan connections.
- Websocket fallbacks.
- Sending missing messages when reconnecting.
- Horizontal scaling.
- Scaling WebSocket in Go and beyond article by Alexander Emelin.
- A Million WebSockets and Go article by Sergey Kamardin.
- Going Infinite, handling 1 millions websockets connections in Go video by Eran Yanay.
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.