lxzan / gws

simple, fast, reliable websocket server & client, supports running over tcp/kcp/unix domain socket. keywords: ws, proxy, chat, go, golang...
https://pkg.go.dev/github.com/lxzan/gws
Apache License 2.0
1.34k stars 84 forks source link

Thread safety of methods WriteMessage, WritePing, WritePong, SetDeadline, WriteClose of gws.Conn #72

Closed Andrey36652 closed 7 months ago

Andrey36652 commented 7 months ago

Hello, I'm considering usage of gws as a websocket client library. I want to ask: is it safe to call methods WriteMessage, WritePing, WritePong, SetDeadline, WriteClose of same gws.Conn concurrently from distinct goroutines?

Example:

socket, _, err := gws.NewClient(...arguments here...)
go socket.ReadLoop()

go socket.WriteMessage(gws.OpcodeText, []byte("message1"))
go socket.SetDeadline(time.Now().Add(10 * time.Seconds))
go socket.WriteMessage(gws.OpcodeText, []byte("message2"))
go socket.WritePing([]byte("ping"))
go socket.WritePong([]byte("pong"))

Or should I wrap with mutex each call of those methods?

lxzan commented 7 months ago

Screenshot_2024-01-16-07-22-21-26_320a9a695de7cdce83ed5281148d6f19.jpg

Andrey36652 commented 7 months ago

Oh, I thought "Concurrent & Asynchronous Non-Blocking Write" applies only to method WriteAsync. So, this statement applies to all of the WriteMessage, WritePing, WritePong, SetDeadline, WriteClose methods, right?

lxzan commented 7 months ago

yes

gws generates a full websocket frame each time it writes, and net.Conn has an internal lock, so developers don't have to lock again when using gws

Andrey36652 commented 7 months ago

net.Conn has an internal lock

Is this implementation platform independent? i.e. same behaviour on Windows, Linux, macos?

lxzan commented 7 months ago

It should be consistent, gws does implementations based on the standard network library

Andrey36652 commented 7 months ago

Thanks