如何在GO中存储WebSocket连接

我要将客户端Websocket连接存储到 wsList </ code>中,并统一发送响应。 但是它将返回“使用封闭的网络连接”。 如何解决? </ p>

  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(){
表示_,conn:= 范围wsList {
如果err:= websocket.JSON.Send(conn,outmsg); err!= nil {
fmt.Printf(“%s”,err)//“使用封闭的网络连接”
}
}
}
</ code> </ pre>
</ DIV>

展开原文

原文

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"
        }
    }
}

duanke0178
duanke0178 我使用code.google.com/p/go.net/websocket
大约 6 年之前 回复
dongtan2017
dongtan2017 您正在使用哪个websocket软件包?
大约 6 年之前 回复

2个回答



您不能简单地假设所有连接无限期保持打开状态,因为另一端可能会随意关闭它们,或者可能发生网络中断,从而迫使它们 </ p>

尝试读取或写入关闭的连接时,也会收到错误消息</ p>

 “使用关闭的连接 网络连接“ 
</ code> </ pre>

您应该丢弃已关闭的连接。</ p>
</ div>

展开原文

原文

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.

duanlu5055
duanlu5055 删除转到此处:转到sendmsg()。
大约 6 年之前 回复
doudi4621
doudi4621 如果是这样,每当我想向它们发送一些数据时,如何维护一个客户端连接列表。
大约 6 年之前 回复
douguanya4248
douguanya4248 无论调用WShandler还是可以关闭连接,是的
大约 6 年之前 回复
doujing6436
doujing6436 但是我在sendmsg中无法获得任何连接,这是否意味着当WShandler()返回时,连接已关闭?
大约 6 年之前 回复

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.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问