Simplify echo example client (#349)

Use existing `done` channel to signal that reader is done instead of closing the connection.
This commit is contained in:
claudia-jones 2018-02-18 16:00:50 -08:00 committed by Gary Burd
parent 4ac909741d
commit 8fbc40be62
1 changed files with 5 additions and 4 deletions

View File

@ -38,7 +38,6 @@ func main() {
done := make(chan struct{})
go func() {
defer c.Close()
defer close(done)
for {
_, message, err := c.ReadMessage()
@ -55,6 +54,8 @@ func main() {
for {
select {
case <-done:
return
case t := <-ticker.C:
err := c.WriteMessage(websocket.TextMessage, []byte(t.String()))
if err != nil {
@ -63,8 +64,9 @@ func main() {
}
case <-interrupt:
log.Println("interrupt")
// To cleanly close a connection, a client should send a close
// frame and wait for the server to close the connection.
// Cleanly close the connection by sending a close message and then
// waiting (with timeout) for the server to close the connection.
err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
log.Println("write close:", err)
@ -74,7 +76,6 @@ func main() {
case <-done:
case <-time.After(time.Second):
}
c.Close()
return
}
}