reading detects the closed connection much quicker than writing. I decided to spin up a go-routine to do my writing, and then my reading was done on the server managed go-routine. I noticed that my read would stop much quicker, and the write would go on for quite awhile before it's err clause triggered. So I used a boolean available to both that if either one errored would break the read/write loops. This helped my server close out more nicely.
func WSServer(ws *websocket.Conn) {
//TODO Set this connection up as a listener for system events
isOpen := true
//Start a go routine to listen
go func() {
for isOpen {
var data Message
err := websocket.JSON.Receive(ws, &data)
if err != nil {
isOpen = false
fmt.Println("Receiver Closing", err)
break
}
fmt.Println("Recieved", data.Msg, data.Count)
}
}()
//Block this routine to send
var count int
for isOpen {
time.Sleep(time.Second)
err := websocket.JSON.Send(ws, Message{"Hello", count})
if err != nil {
isOpen = false
fmt.Println("Sender Closing", err)
break
}
fmt.Println("Sent", count)
count++
}
//TODO Cleanup
//Remove the connection from all channels it is subscribed to