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"
}
}
}
The connection ws
is closed when WsHandler
returns. To fix the problem, prevent WsHandler
from 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.
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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.