Skip to content

Commit

Permalink
Merge pull request #118 from Jardaliao/fix-closing-connection-returns…
Browse files Browse the repository at this point in the history
…-invalid-code

fix: closing websocket connection returns invalid status code
  • Loading branch information
AlexStocks authored Apr 25, 2024
2 parents a5233ed + 4d36106 commit ce6736e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
21 changes: 21 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import (
)

import (
"github.com/gorilla/websocket"
"github.com/stretchr/testify/assert"
)

Expand Down Expand Up @@ -352,6 +353,26 @@ func TestNewWSClient(t *testing.T) {
err = conn.writePing()
assert.Nil(t, err)

done := make(chan int)
conn.conn.SetCloseHandler(func(code int, text string) error {
defer func() {
done <- code
close(done)
}()
message := websocket.FormatCloseMessage(code, "")
conn.conn.WriteControl(websocket.CloseMessage, message, time.Now().Add(1e9))
return nil
})
serverSession := serverMsgHandler.array[0]
serverSession.Close()
select {
case code := <-done:
assert.True(t, code == websocket.CloseNormalClosure)
case <-time.After(5e9):
assert.True(t, false)
}
assert.True(t, serverSession.IsClosed())

ss.SetReader(nil)
assert.Nil(t, ss.(*session).reader)
ss.SetWriter(nil)
Expand Down
2 changes: 1 addition & 1 deletion connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -628,7 +628,7 @@ func (w *gettyWSConn) writePong(message []byte) error {
// close websocket connection
func (w *gettyWSConn) CloseConn(waitSec int) {
w.updateWriteDeadline()
w.conn.WriteMessage(websocket.CloseMessage, []byte("bye-bye!!!"))
w.conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "bye-bye!!!"))
conn := w.conn.UnderlyingConn()
if tcpConn, ok := conn.(*net.TCPConn); ok {
tcpConn.SetLinger(waitSec)
Expand Down

0 comments on commit ce6736e

Please sign in to comment.