修正websocket连接断开问题

This commit is contained in:
lwch
2023-03-09 16:42:17 +08:00
parent d1989baf7b
commit e65f397308
2 changed files with 9 additions and 3 deletions

8
app.go
View File

@@ -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

View File

@@ -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()
}
}
}