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

PHPz
Release: 2024-02-08 20:45:09
forward
422 people have browsed it

如何在 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)
    …
Copy after login

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

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!