Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix concurrent panic #67

Merged
merged 1 commit into from Sep 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 8 additions & 7 deletions melody.go
Expand Up @@ -174,13 +174,14 @@ func (m *Melody) HandleRequestWithKeys(w http.ResponseWriter, r *http.Request, k
}

session := &Session{
Request: r,
Keys: keys,
conn: conn,
output: make(chan *envelope, m.Config.MessageBufferSize),
melody: m,
open: true,
rwmutex: &sync.RWMutex{},
Request: r,
Keys: keys,
conn: conn,
output: make(chan *envelope, m.Config.MessageBufferSize),
outputDone: make(chan struct{}),
melody: m,
open: true,
rwmutex: &sync.RWMutex{},
}

m.hub.register <- session
Expand Down
36 changes: 19 additions & 17 deletions session.go
Expand Up @@ -11,13 +11,14 @@ import (

// Session wrapper around websocket connections.
type Session struct {
Request *http.Request
Keys map[string]interface{}
conn *websocket.Conn
output chan *envelope
melody *Melody
open bool
rwmutex *sync.RWMutex
Request *http.Request
Keys map[string]interface{}
conn *websocket.Conn
output chan *envelope
outputDone chan struct{}
melody *Melody
open bool
rwmutex *sync.RWMutex
}

func (s *Session) writeMessage(message *envelope) {
Expand Down Expand Up @@ -56,12 +57,13 @@ func (s *Session) closed() bool {
}

func (s *Session) close() {
if !s.closed() {
s.rwmutex.Lock()
s.open = false
s.rwmutex.Lock()
open := s.open
s.open = false
s.rwmutex.Unlock()
if open {
s.conn.Close()
close(s.output)
s.rwmutex.Unlock()
close(s.outputDone)
}
}

Expand All @@ -76,11 +78,7 @@ func (s *Session) writePump() {
loop:
for {
select {
case msg, ok := <-s.output:
if !ok {
break loop
}

case msg := <-s.output:
err := s.writeRaw(msg)

if err != nil {
Expand All @@ -101,6 +99,10 @@ loop:
}
case <-ticker.C:
s.ping()
case _, ok := <-s.outputDone:
if !ok {
break loop
}
}
}
}
Expand Down