From e65f397308474c973e46db07fddc085ce005abea Mon Sep 17 00:00:00 2001 From: lwch Date: Thu, 9 Mar 2023 16:42:17 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=AD=A3websocket=E8=BF=9E=E6=8E=A5?= =?UTF-8?q?=E6=96=AD=E5=BC=80=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app.go | 8 +++++--- app_handler.go | 4 ++++ 2 files changed, 9 insertions(+), 3 deletions(-) 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() } } }