Skip to content

Commit 6834c14

Browse files
committed
fix the issue with the 'ReadMessage' thread not exiting when 'stopCh' is triggered
1 parent d37282f commit 6834c14

File tree

1 file changed

+20
-21
lines changed

1 file changed

+20
-21
lines changed

websocket.go

Lines changed: 20 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -66,36 +66,19 @@ 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)
7473
if WebsocketKeepalive {
7574
keepAlive(c, WebsocketTimeout)
7675
}
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-
}()
76+
// Separate goroutine to handle message reading
77+
go readMessages(c, handler, errHandler, stopCh)
9478

9579
for {
9680
select {
9781
case <-stopCh:
98-
silent = true
9982
return
10083
case <-doneCh:
10184
}
@@ -104,6 +87,22 @@ var wsServe = func(cfg *WsConfig, handler WsHandler, errHandler ErrHandler) (don
10487
return
10588
}
10689

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

0 commit comments

Comments
 (0)