[英]How to store websocket connection in GO
I want to store client websocket connection into wsList
, and send response in uniform. 我想将客户端websocket连接存储到
wsList
,并统一发送响应。 but it will return "use of closed network connection". 但是它将返回“使用封闭的网络连接”。 How to fix it?
如何解决?
import {
"code.google.com/p/go.net/websocket"
...
}
var wsList []*websocket.Conn
func WShandler(ws *websocket.Conn) {
wsList = append(wsList, ws)
go sendmsg()
}
func sendmsg() {
for _, conn := range wsList {
if err := websocket.JSON.Send(conn, outmsg); err != nil {
fmt.Printf("%s", err) //"use of closed network connection"
}
}
}
The connection ws
is closed when WsHandler
returns. WsHandler
返回时,连接ws
关闭。 To fix the problem, prevent WsHandler
from returning by reading messages in a loop until an error is detected: 要解决此问题,请通过循环读取消息直到检测到错误来防止
WsHandler
返回:
func WShandler(ws *websocket.Conn) {
wsList = append(wsList, ws)
go sendmsg()
for {
var s string
if err := websocket.Message.Receive(ws, &s); err != nil {
break
}
}
// remove ws from wsList here
}
There's a race on wsList. wsList上有一场比赛。 Protect it with a mutex.
用互斥锁保护它。
You cannot simply assume all connections to stay open indefinitely because the other end may close them at will or a network outage may occur, forcing them to close as well. 您不能简单地假设所有连接无限期保持打开状态,因为另一端可能会随意关闭它们,或者可能会发生网络中断,从而迫使它们也关闭。
When you try to read or write to a closed connection, you get an error 当您尝试读取或写入关闭的连接时,会出现错误
"use of closed network connection"
You should discard closed connections. 您应该丢弃关闭的连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.