Domanda

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"
        }
    }
}
È stato utile?

Soluzione 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.

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top