Skip to content

Commit 52df374

Browse files
committed
fix the issue with the 'ReadMessage' thread not exiting when 'stopCh' is triggered
1 parent 9500214 commit 52df374

File tree

1 file changed

+22
-22
lines changed

1 file changed

+22
-22
lines changed

websocket.go

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -66,44 +66,44 @@ var wsServe = func(cfg *WsConfig, handler WsHandler, errHandler ErrHandler) (don
6666
c.SetReadLimit(655350)
6767
doneCh = make(chan struct{})
6868
stopCh = make(chan struct{})
69+
6970
go func() {
70-
// This function will exit either on error from
71-
// websocket.Conn.ReadMessage or when the stopC channel is
72-
// closed by the client.
7371
defer close(doneCh)
72+
defer close(stopCh)
73+
defer c.Close()
7474
if WebsocketKeepalive {
7575
keepAlive(c, WebsocketTimeout)
7676
}
77-
// Wait for the stopC channel to be closed. We do that in a
78-
// separate goroutine because ReadMessage is a blocking
79-
// operation.
80-
silent := false
81-
go func() {
82-
for {
83-
_, message, err := c.ReadMessage()
84-
if err != nil {
85-
if !silent {
86-
errHandler(err)
87-
}
88-
stopCh <- struct{}{}
89-
return
90-
}
91-
handler(message)
92-
}
93-
}()
77+
// Separate goroutine to handle message reading
78+
go readMessages(c, handler, errHandler, doneCh, stopCh)
9479

9580
for {
9681
select {
9782
case <-stopCh:
98-
silent = true
9983
return
100-
case <-doneCh:
10184
}
10285
}
10386
}()
10487
return
10588
}
10689

90+
func readMessages(c *websocket.Conn, handler WsHandler, errHandler ErrHandler, doneCh, stopCh chan struct{}) {
91+
for {
92+
select {
93+
case <-doneCh:
94+
return
95+
default:
96+
_, message, err := c.ReadMessage()
97+
if err != nil {
98+
errHandler(err)
99+
stopCh <- struct{}{}
100+
return
101+
}
102+
handler(message)
103+
}
104+
}
105+
}
106+
107107
func keepAlive(c *websocket.Conn, timeout time.Duration) {
108108
ticker := time.NewTicker(timeout)
109109

0 commit comments

Comments
 (0)