@@ -493,8 +493,9 @@ func (u *gettyUDPConn) CloseConn(_ int) {
493
493
494
494
type gettyWSConn struct {
495
495
gettyConn
496
- conn * websocket.Conn
497
- lock sync.Mutex
496
+ writeLock sync.Mutex
497
+ readLock sync.Mutex
498
+ conn * websocket.Conn
498
499
}
499
500
500
501
// create websocket connection
@@ -569,7 +570,7 @@ func (w *gettyWSConn) handlePong(string) error {
569
570
func (w * gettyWSConn ) recv () ([]byte , error ) {
570
571
// Pls do not set read deadline when using ReadMessage. AlexStocks 20180310
571
572
// gorilla/websocket/conn.go:NextReader will always fail when got a timeout error.
572
- _ , b , e := w .conn . ReadMessage () // the first return value is message type.
573
+ _ , b , e := w .threadSafeReadMessage () // the first return value is message type.
573
574
if e == nil {
574
575
w .readBytes .Add ((uint32 )(len (b )))
575
576
} else {
@@ -643,12 +644,23 @@ func (w *gettyWSConn) CloseConn(waitSec int) {
643
644
w .conn .Close ()
644
645
}
645
646
646
- // uses a mutex to ensure that only one thread can send a message at a time, preventing race conditions.
647
+ // uses a mutex(writeLock) to ensure that only one thread can send a message at a time, preventing race conditions.
647
648
func (w * gettyWSConn ) threadSafeWriteMessage (messageType int , data []byte ) error {
648
- w .lock .Lock ()
649
- defer w .lock .Unlock ()
649
+ w .writeLock .Lock ()
650
+ defer w .writeLock .Unlock ()
650
651
if err := w .conn .WriteMessage (messageType , data ); err != nil {
651
652
return err
652
653
}
653
654
return nil
654
655
}
656
+
657
+ // uses a mutex(readLock) to ensure that only one thread can read a message at a time, preventing race conditions.
658
+ func (w * gettyWSConn ) threadSafeReadMessage () (int , []byte , error ) {
659
+ w .readLock .Lock ()
660
+ defer w .readLock .Unlock ()
661
+ messageType , readBytes , err := w .conn .ReadMessage ()
662
+ if err != nil {
663
+ return messageType , nil , err
664
+ }
665
+ return messageType , readBytes , nil
666
+ }
0 commit comments