英文:
How to listen on a server-side websocket non-blocking in Go
问题
我使用https://pkg.go.dev/golang.org/x/net/websocket来创建一个服务器端的websocket。所有的通信都是通过JSON进行的。因此,我的代码包含以下内容:
func wsHandler(ws *websocket.Conn) {
var evnt event
websocket.JSON.Receive(ws, &evnt)
…
}
然而,这个代码会一直阻塞,直到客户端关闭连接。我知道这个websocket包是在context出现之前发布的(我也知道有更新的websocket包),但是,难道真的没有一种非阻塞的方式来等待传入的帧吗?
英文:
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
得分: 1
这个代码块会阻塞,直到客户端关闭连接。
处理并发阻塞操作的最简单方法是使用goroutine。与进程或线程不同,goroutine基本上是“免费的”。
func wsHandler(ws *websocket.Conn) {
go func() {
var evnt event
websocket.JSON.Receive(ws, &evnt)
....
}()
}
英文:
> 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)
....
}()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论