Home >Backend Development >Golang >How to non-blockingly listen to a server-side websocket in Go

How to non-blockingly listen to a server-side websocket in Go

PHPz
PHPzforward
2024-02-08 20:45:09451browse

如何在 Go 中非阻塞地监听服务器端 websocket

Question content

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?


Correct answer


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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete