How to listen on a server-side websocket non-blocking in Go

329 Views Asked by At

I use https://pkg.go.dev/golang.org/x/net/websocket for creating a server-side websocket. All communication through it is in JSON. Thus, my code contains:

func wsHandler(ws *websocket.Conn) {
    var evnt event
    websocket.JSON.Receive(ws, &evnt)
    …

However, this blocks until the connection is closed by the client. I know that this websocket package pre-dates context (and I know that there are newer websocket packages), still – is there really no way to wait for incoming frames in a non-blocking way?

1

There are 1 best solutions below

0
erik258 On BEST ANSWER

this blocks until the connection is closed by the client.

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)
      ....
   }()
}