문제

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

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top