Note: I’m more interested in understanding general Go concepts/patterns, rather than solving this contrived example.
The Go (golang) WebSocket package provides a trivial echo server example, which condenses down to something like this:
func EchoServer(ws *websocket.Conn) { io.Copy(ws, ws); }
func main() {
http.Handle("/echo", websocket.Handler(EchoServer));
http.ListenAndServe(":12345", nil);
}
The server handles simultaneous connections, and I’m trying to upgrade it to a basic chat server by echoing the input to all connected clients.
How would I go about providing the EchoServer handler access to each of the open connections?
A quick little almost-functional example to give you an idea
This starts a goroutine that listens on two channels, one for new connections to add and one for messages to send to all active connection.
somekindofstoragecould be a map or a vector.Edit:
Alternatively, you could just store all connections in a global map and write to each from
EchoServer. But maps aren’t designed to be accessed concurrently.