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

huangapple go评论99阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年7月23日 00:36:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76744859.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定