Search code examples
gowebsocketservernonblockinggo-context

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


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?


Solution

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