Skip to content

Commit

Permalink
websocket: serialize the order of the session set and get
Browse files Browse the repository at this point in the history
  • Loading branch information
lesismal committed Oct 10, 2023
1 parent 130b7cd commit 277de28
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
22 changes: 21 additions & 1 deletion nbhttp/websocket/conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ type Conn struct {

mux sync.Mutex

session interface{}
chSessionInited chan struct{}
session interface{}

sendQueue [][]byte
sendQueueSize int
Expand Down Expand Up @@ -96,6 +97,13 @@ func (c *Conn) IsAsyncWrite() bool {

// Close .
func (c *Conn) Close() error {
c.mux.Lock()
if c.chSessionInited != nil {
close(c.chSessionInited)
c.chSessionInited = nil
}
c.mux.Unlock()

if c.Conn == nil {
return nil
}
Expand Down Expand Up @@ -563,11 +571,23 @@ func (c *Conn) WriteMessage(messageType MessageType, data []byte) error {

// Session returns user session.
func (c *Conn) Session() interface{} {
c.mux.Lock()
ch := c.chSessionInited
c.mux.Unlock()
if ch != nil {
<-ch
}
return c.session
}

// SetSession sets user session.
func (c *Conn) SetSession(session interface{}) {
c.mux.Lock()
if c.chSessionInited != nil {
close(c.chSessionInited)
c.chSessionInited = nil
}
c.mux.Unlock()
c.session = session
}

Expand Down
1 change: 1 addition & 0 deletions nbhttp/websocket/upgrader.go
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,7 @@ func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeade

if wsc.isBlockingMod {
if parser == nil {
wsc.chSessionInited = make(chan struct{})
go wsc.BlockingModReadLoop(u.BlockingModReadBufferSize)
}
}
Expand Down

0 comments on commit 277de28

Please sign in to comment.