go-chat icon indicating copy to clipboard operation
go-chat copied to clipboard

并发安全

Open ykaii opened this issue 1 year ago • 1 comments

gorilla/websocket的文档写道: Connections support one concurrent reader and one concurrent writer.

Applications are responsible for ensuring that no more than one goroutine calls the write methods (NextWriter, SetWriteDeadline, WriteMessage, WriteJSON, EnableWriteCompression, SetCompressionLevel) concurrently and that no more than one goroutine calls the read methods (NextReader, SetReadDeadline, ReadMessage, ReadJSON, SetPongHandler, SetPingHandler) concurrently.

The Close and WriteControl methods can be called concurrently with all other methods.

所以在读写websocket消息的两个goroutine中并发调用WriteMessage方法是不可以的

ykaii avatar Mar 22 '23 01:03 ykaii

感谢提醒,在Client对象里面添加mu sync.Mutex互斥锁,调用Conn *websocket.Conn 写消息时,应该加锁和释放锁。

kone-net avatar Apr 19 '23 03:04 kone-net