diff --git a/app.go b/app.go index f6a6c6c..55f92ff 100644 --- a/app.go +++ b/app.go @@ -6,6 +6,7 @@ import ( "os" "path/filepath" rt "runtime" + "sync" "time" "github.com/jkstack/anet" @@ -22,9 +23,10 @@ type app struct { chWrite chan *anet.Msg // runtime - ctx context.Context - cancel context.CancelFunc - connected bool + ctx context.Context + cancel context.CancelFunc + connected bool + mWriteLock sync.Mutex // monitor inPackets, inBytes uint64 diff --git a/app_handler.go b/app_handler.go index 408b313..6978bb1 100644 --- a/app_handler.go +++ b/app_handler.go @@ -61,7 +61,9 @@ func (app *app) write(ctx context.Context, cancel context.CancelFunc, conn *webs return } + app.mWriteLock.Lock() err = conn.WriteMessage(websocket.TextMessage, data) + app.mWriteLock.Unlock() if err != nil { logging.Error("write message: %v", err) return @@ -89,7 +91,9 @@ func (app *app) keepalive(ctx context.Context, conn *websocket.Conn) { case <-ctx.Done(): return case <-tk.C: + app.mWriteLock.Lock() conn.WriteControl(websocket.PingMessage, nil, time.Now().Add(2*time.Second)) + app.mWriteLock.Unlock() } } }