gorilla / websocket

Package gorilla/websocket is a fast, well-tested and widely used WebSocket implementation for Go.
https://gorilla.github.io
BSD 2-Clause "Simplified" License
22.03k stars 3.47k forks source link

[BUG] panic: concurrent write to websocket connection #913

Closed gzw13999 closed 1 week ago

gzw13999 commented 4 months ago

Is there an existing issue for this?

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/websocket@v1.5.1/conn.go:632 +0x4b8
github.com/gorilla/websocket.(*messageWriter).Close(0x1306a90?)
    D:/projects/go/pkg/mod/github.com/gorilla/websocket@v1.5.1/conn.go:746 +0x35
github.com/gorilla/websocket.(*Conn).beginMessage(0xc0012d0160, 0xc000ea8a50, 0x1)
    D:/projects/go/pkg/mod/github.com/gorilla/websocket@v1.5.1/conn.go:493 +0x47
github.com/gorilla/websocket.(*Conn).NextWriter(0xc0012d0160, 0x1)
    D:/projects/go/pkg/mod/github.com/gorilla/websocket@v1.5.1/conn.go:535 +0x3f
github.com/gorilla/websocket.(*Conn).WriteJSON(0xba577e?, {0xaaa0e0, 0xc000ea8a20})
    D:/projects/go/pkg/mod/github.com/gorilla/websocket@v1.5.1/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

gzw13999 commented 4 months ago

Got it, it turns out concurrency is not supported

ghost commented 4 months ago

The documentation describes the allowed concurrency. Concurrent writes are not allowed.

A quick fix is to protect write to the connection with a mutex.

gzw13999 commented 4 months ago

Thank you, got it

MikMuellerDev commented 1 month ago

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.

hulkingshtick commented 1 week ago

This issue should be closed. The application writes to the connection concurrently.