Add mutex to prevent concurrent connection write

This commit is contained in:
Justin Powell 2016-10-25 11:50:59 -07:00 committed by GitHub
parent 0b847f2fac
commit 675dff59e9
1 changed files with 6 additions and 0 deletions

View File

@ -8,6 +8,7 @@ import (
"bytes" "bytes"
"log" "log"
"net/http" "net/http"
"sync"
"time" "time"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
@ -46,6 +47,9 @@ type Client struct {
// Buffered channel of outbound messages. // Buffered channel of outbound messages.
send chan []byte send chan []byte
// Mutex to prevent concurrent connection write
mux sync.Mutex
} }
// readPump pumps messages from the websocket connection to the hub. // 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. // write writes a message with the given message type and payload.
func (c *Client) write(mt int, payload []byte) error { func (c *Client) write(mt int, payload []byte) error {
c.mux.Lock()
defer c.mux.Unlock()
c.conn.SetWriteDeadline(time.Now().Add(writeWait)) c.conn.SetWriteDeadline(time.Now().Add(writeWait))
return c.conn.WriteMessage(mt, payload) return c.conn.WriteMessage(mt, payload)
} }