websocket icon indicating copy to clipboard operation
websocket copied to clipboard

[BUG] panic: concurrent write to websocket connection

Open gzw13999 opened this issue 10 months ago • 5 comments

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

gzw13999 avatar Apr 29 '24 17:04 gzw13999

Got it, it turns out concurrency is not supported

gzw13999 avatar Apr 29 '24 17:04 gzw13999

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

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

ghost avatar Apr 29 '24 20:04 ghost

Thank you, got it

gzw13999 avatar Apr 30 '24 15:04 gzw13999

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.

MikMuellerDev avatar Jul 28 '24 11:07 MikMuellerDev

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

hulkingshtick avatar Aug 28 '24 17:08 hulkingshtick