From d2c3b90bc4af4e397259e527dd56b3c1d6fc89d9 Mon Sep 17 00:00:00 2001 From: Eryx Date: Tue, 16 Oct 2018 13:05:14 +0800 Subject: [PATCH 1/2] Fix panic error in concurrent calling with websocket.Connection.Emit() Former-commit-id: b5d0ecd61547a297c320867af0a8abf208f0f743 --- websocket/server.go | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/websocket/server.go b/websocket/server.go index f704a05e..4055d0d5 100644 --- a/websocket/server.go +++ b/websocket/server.go @@ -52,9 +52,9 @@ type ( func New(cfg Config) *Server { cfg = cfg.Validate() return &Server{ - config: cfg, - connections: sync.Map{}, // ready-to-use, this is not necessary. - rooms: make(map[string][]string), + config: cfg, + connections: sync.Map{}, // ready-to-use, this is not necessary. + rooms: make(map[string][]string), onConnectionListeners: make([]ConnectionFunc, 0), upgrader: websocket.Upgrader{ HandshakeTimeout: cfg.HandshakeTimeout, @@ -352,7 +352,10 @@ func (s *Server) GetConnectionsByRoom(roomName string) []Connection { // let's keep it unexported for the best. func (s *Server) emitMessage(from, to string, data []byte) { if to != All && to != Broadcast { - if s.rooms[to] != nil { + s.mu.RLock() + room := s.rooms[to] + s.mu.RUnlock() + if room != nil { // it suppose to send the message to a specific room/or a user inside its own room for _, connectionIDInsideRoom := range s.rooms[to] { if c, ok := s.getConnection(connectionIDInsideRoom); ok { From 1f1dfcca1ce0cdb361398e4198e0bf3445cf9805 Mon Sep 17 00:00:00 2001 From: Eryx Date: Tue, 16 Oct 2018 13:25:28 +0800 Subject: [PATCH 2/2] Fix panic error in concurrent calling with websocket.Connection.Emit() Former-commit-id: 4c5cc222e9a43b18a86adb35bfafe4a278fd880e --- websocket/server.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/websocket/server.go b/websocket/server.go index 4055d0d5..a88f1806 100644 --- a/websocket/server.go +++ b/websocket/server.go @@ -357,7 +357,7 @@ func (s *Server) emitMessage(from, to string, data []byte) { s.mu.RUnlock() if room != nil { // it suppose to send the message to a specific room/or a user inside its own room - for _, connectionIDInsideRoom := range s.rooms[to] { + for _, connectionIDInsideRoom := range room { if c, ok := s.getConnection(connectionIDInsideRoom); ok { c.writeDefault(data) //send the message to the client(s) } else {