From 675dff59e9bc1f1f44cc3c6ca9d64c5c6ebeadc7 Mon Sep 17 00:00:00 2001 From: Justin Powell Date: Tue, 25 Oct 2016 11:50:59 -0700 Subject: [PATCH] Add mutex to prevent concurrent connection write --- examples/chat/client.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/examples/chat/client.go b/examples/chat/client.go index c3c518d..d5cdf73 100644 --- a/examples/chat/client.go +++ b/examples/chat/client.go @@ -8,6 +8,7 @@ import ( "bytes" "log" "net/http" + "sync" "time" "github.com/gorilla/websocket" @@ -46,6 +47,9 @@ type Client struct { // Buffered channel of outbound messages. send chan []byte + + // Mutex to prevent concurrent connection write + mux sync.Mutex } // readPump pumps messages from the websocket connection to the hub. @@ -72,6 +76,8 @@ func (c *Client) readPump() { // write writes a message with the given message type and payload. func (c *Client) write(mt int, payload []byte) error { + c.mux.Lock() + defer c.mux.Unlock() c.conn.SetWriteDeadline(time.Now().Add(writeWait)) return c.conn.WriteMessage(mt, payload) }