Jerry YY Rain
Jerry YY Rain

Reputation: 4382

How to store websocket connection in GO

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

Upvotes: 2

Views: 2446

Answers (2)

Thundercat
Thundercat

Reputation: 120941

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.

Upvotes: 4

thwd
thwd

Reputation: 24808

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.

Upvotes: 2

Related Questions