Skip to content

Commit 8fbc40b

Browse files
claudia-jonesgaryburd
authored andcommitted
Simplify echo example client (#349)
Use existing `done` channel to signal that reader is done instead of closing the connection.
1 parent 4ac9097 commit 8fbc40b

File tree

1 file changed

+5
-4
lines changed

1 file changed

+5
-4
lines changed

examples/echo/client.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@ func main() {
3838
done := make(chan struct{})
3939

4040
go func() {
41-
defer c.Close()
4241
defer close(done)
4342
for {
4443
_, message, err := c.ReadMessage()
@@ -55,6 +54,8 @@ func main() {
5554

5655
for {
5756
select {
57+
case <-done:
58+
return
5859
case t := <-ticker.C:
5960
err := c.WriteMessage(websocket.TextMessage, []byte(t.String()))
6061
if err != nil {
@@ -63,8 +64,9 @@ func main() {
6364
}
6465
case <-interrupt:
6566
log.Println("interrupt")
66-
// To cleanly close a connection, a client should send a close
67-
// frame and wait for the server to close the connection.
67+
68+
// Cleanly close the connection by sending a close message and then
69+
// waiting (with timeout) for the server to close the connection.
6870
err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
6971
if err != nil {
7072
log.Println("write close:", err)
@@ -74,7 +76,6 @@ func main() {
7476
case <-done:
7577
case <-time.After(time.Second):
7678
}
77-
c.Close()
7879
return
7980
}
8081
}

0 commit comments

Comments
 (0)