websocket
websocket copied to clipboard
[BUG] panic: concurrent write to websocket connection
Is there an existing issue for this?
- [X] I have searched the existing issues
Current Behavior
I used about 10 goroutines to execute the conn.WriteJSON method concurrently, and the following panic occurred:
goroutine 18450 [running]:
github.com/gorilla/websocket.(*messageWriter).flushFrame(0xc000ea8990, 0x1, {0x0?, 0x0?, 0x0?})
D:/projects/go/pkg/mod/github.com/gorilla/[email protected]/conn.go:632 +0x4b8
github.com/gorilla/websocket.(*messageWriter).Close(0x1306a90?)
D:/projects/go/pkg/mod/github.com/gorilla/[email protected]/conn.go:746 +0x35
github.com/gorilla/websocket.(*Conn).beginMessage(0xc0012d0160, 0xc000ea8a50, 0x1)
D:/projects/go/pkg/mod/github.com/gorilla/[email protected]/conn.go:493 +0x47
github.com/gorilla/websocket.(*Conn).NextWriter(0xc0012d0160, 0x1)
D:/projects/go/pkg/mod/github.com/gorilla/[email protected]/conn.go:535 +0x3f
github.com/gorilla/websocket.(*Conn).WriteJSON(0xba577e?, {0xaaa0e0, 0xc000ea8a20})
D:/projects/go/pkg/mod/github.com/gorilla/[email protected]/json.go:24 +0x34
github.com/gzw13999/gows/spot.(*Api).CancelOrder(0xc000185960, {{0xc0012afca0, 0x8}, {0x0, 0x0}, {0x0, 0x0}, 0x2, 0x5, 0x0, ...}, ...)
D:/projects/go/src/github.com/gzw13999/gows/prv.go:285 +0x369
github.com/gzw13999/qu/strat.(*Strategy5).cancelOrder(...)
Can't conn.WriteJSON be executed concurrently?
Expected Behavior
There should not be a panic that causes the program to terminate.
Steps To Reproduce
The access is to a third-party API and no recurrence pattern has been found yet.
Anything else?
No response
Got it, it turns out concurrency is not supported
The documentation describes the allowed concurrency. Concurrent writes are not allowed.
A quick fix is to protect write to the connection with a mutex.
Thank you, got it
A thing that i have done many times is to wrap the Websocket connection in a struct, together with a Mutex in a custom struct and making a few methods 'public'. Therefore, you have a 'LockedConn' struct which hides the lock completely.
This issue should be closed. The application writes to the connection concurrently.