Home > Article > Backend Development > How to non-blockingly listen to a server-side websocket in Go
I use https://pkg.go.dev/golang.org/x/net/websocket to create a server-side websocket. All communication through it is in json format. So my code contains:
func wsHandler(ws *websocket.Conn) { var evnt event websocket.JSON.Receive(ws, &evnt) …
However, this blocks until the client closes the connection. I know this websocket package predates context (and I know there are newer websocket packages), but still - is there really no way to wait for incoming frames in a non-blocking way?
This blocks until the client closes the connection.
The easiest way to handle concurrent blocking operations is to give them a goroutine. Goroutines, unlike processes or threads, are essentially "free".
func wsHandler(ws *websocket.Conn) { go func() { var evnt event websocket.JSON.Receive(ws, &evnt) .... }() }
The above is the detailed content of How to non-blockingly listen to a server-side websocket in Go. For more information, please follow other related articles on the PHP Chinese website!