doudao5287
doudao5287
2014-05-12 11:30
浏览 269
已采纳

如何在GO中存储WebSocket连接

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"
        }
    }
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanbichenhe1968
    duanbichenhe1968 2014-05-12 11:42
    已采纳

    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.

    点赞 评论
  • dongtang6681
    dongtang6681 2016-02-02 07:56

    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.

    点赞 评论

相关推荐