英文:
How to store websocket connection in GO
问题
我想将客户端的 WebSocket 连接存储到 wsList 中,并统一发送响应。但是它会返回 "use of closed network connection"。如何修复这个问题?
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"
        }
    }
}
你可以在 sendmsg 函数中添加错误处理,检查连接是否已关闭。可以使用 websocket.JSON.Send 方法的返回值来判断连接是否关闭,如果连接已关闭,则不再发送消息。例如:
func sendmsg() {
    for _, conn := range wsList {
        if websocket.JSON.Send(conn, outmsg) != nil {
            if websocket.IsCloseError(err, websocket.CloseNormalClosure) {
                // 连接已关闭,不再发送消息
                continue
            }
            fmt.Printf("%s", err)
        }
    }
}
这样,当连接已关闭时,就不会再尝试发送消息,避免了 "use of closed network connection" 的错误。
英文:
I want to store client websocket connection into wsList, and send response in uniform. 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"
        }
    }
}
答案1
得分: 3
连接ws在WsHandler返回时关闭。为了解决这个问题,可以通过在循环中读取消息直到检测到错误来防止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
     }
  }
  // 在这里从wsList中移除ws
}
wsList存在竞态条件。可以使用互斥锁来保护它。
英文:
The connection ws is closed when WsHandler returns.  To fix the problem, prevent WsHandlerfrom returning by reading messages in a loop until an error is detected:
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. Protect it with a mutex.
答案2
得分: 2
你不能简单地假设所有的连接会无限期地保持打开状态,因为另一端可能会随意关闭它们,或者可能发生网络故障,迫使它们关闭。
当你尝试读取或写入一个已关闭的连接时,会出现错误信息:
"使用已关闭的网络连接"
你应该丢弃已关闭的连接。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论