Improve client disconnect detection

This commit is contained in:
2024-06-27 11:05:30 +02:00
parent 4acb89cdb1
commit 4ca3053243
3 changed files with 60 additions and 41 deletions

View File

@@ -3,12 +3,14 @@ package main
import ( import (
"log" "log"
"sync" "sync"
"sync/atomic"
"time" "time"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
) )
type WSConnection struct { type WSConnection struct {
id int32
conn *websocket.Conn conn *websocket.Conn
writeLock sync.Mutex writeLock sync.Mutex
alive bool alive bool
@@ -21,6 +23,7 @@ type WSConnection struct {
func NewConn(conn *websocket.Conn, server *WSServer) *WSConnection { func NewConn(conn *websocket.Conn, server *WSServer) *WSConnection {
wsconn := &WSConnection{ wsconn := &WSConnection{
id: server.clientId,
conn: conn, conn: conn,
alive: true, alive: true,
IdleTimeout: server.IdleTimeout, IdleTimeout: server.IdleTimeout,
@@ -29,6 +32,7 @@ func NewConn(conn *websocket.Conn, server *WSServer) *WSConnection {
WriteChan: make(chan string, 1024), WriteChan: make(chan string, 1024),
ErrorChan: make(chan error, 1), ErrorChan: make(chan error, 1),
} }
atomic.AddInt32(&server.clientId, 1)
return wsconn return wsconn
} }
@@ -36,11 +40,16 @@ func NewConn(conn *websocket.Conn, server *WSServer) *WSConnection {
func (ws *WSConnection) Open() { func (ws *WSConnection) Open() {
go ws.messageReader() go ws.messageReader()
go ws.messageSender() go ws.messageSender()
// go ws.pinger() go ws.pinger()
ws.conn.SetPongHandler(func(string) error {
// log.Printf("Client %d: Pong OK", ws.id)
ws.conn.SetReadDeadline(time.Now().Add(ws.IdleTimeout))
return nil
})
} }
func (ws *WSConnection) messageReader() { func (ws *WSConnection) messageReader() {
log.Printf("Reading messages") log.Printf("Client %d: Reading messages", ws.id)
for { for {
_, message, err := ws.conn.ReadMessage() _, message, err := ws.conn.ReadMessage()
if !ws.alive { if !ws.alive {
@@ -51,48 +60,52 @@ func (ws *WSConnection) messageReader() {
ws.ErrorChan <- err ws.ErrorChan <- err
return return
} }
log.Printf("Received: %s, %d in output channel", message, len(ws.ReadChan)) log.Printf("Client %d: Received: %s, %d in output channel", ws.id, message, len(ws.ReadChan))
ws.ReadChan <- string(message) ws.ReadChan <- string(message)
} }
} }
func (ws *WSConnection) messageSender() { func (ws *WSConnection) messageSender() {
log.Printf("Sending messages") log.Printf("Client %d: Sending messages", ws.id)
for { for {
msg := <-ws.WriteChan func() {
if !ws.alive { msg, ok := <-ws.WriteChan
return if !ok || !ws.alive {
} return
ws.writeLock.Lock() }
ws.writeLock.Lock()
ws.conn.SetWriteDeadline(time.Now().Add(ws.IdleTimeout)) defer ws.writeLock.Unlock()
log.Printf("Sending: %s, %d in input channel", msg, len(ws.WriteChan))
err := ws.conn.WriteMessage(websocket.TextMessage, []byte(msg)) ws.conn.SetWriteDeadline(time.Now().Add(ws.IdleTimeout))
if err != nil { log.Printf("Client %d: Sending: %s, %d in input channel", ws.id, msg, len(ws.WriteChan))
log.Printf("Error during message writing: %v", err) err := ws.conn.WriteMessage(websocket.TextMessage, []byte(msg))
ws.ErrorChan <- err if err != nil {
return log.Printf("Client %d: Error during message writing: %v", ws.id, err)
} ws.ErrorChan <- err
ws.writeLock.Unlock() return
}
}()
} }
} }
// func (ws *WSConnection) pinger() { func (ws *WSConnection) pinger() {
// log.Printf("Starting pinger, sleeping for %v", ws.PingInterval) log.Printf("Client %d: Starting pinger, sleeping for %v", ws.id, ws.PingInterval)
// for { for {
// time.Sleep(ws.PingInterval) time.Sleep(ws.PingInterval)
// if !ws.alive { if !ws.alive {
// return return
// } }
// log.Printf("Ping") // log.Printf("Client %d: Ping", ws.id)
// ws.writeLock.Lock() ws.writeLock.Lock()
// err := ws.conn.WriteMessage(websocket.PingMessage, nil) err := ws.conn.WriteMessage(websocket.PingMessage, nil)
// if err != nil { if err != nil {
// log.Println("Error during ping:", err) log.Printf("Client %d: Error during ping: %+v", ws.id, err)
// ws.ErrorChan <- err ws.ErrorChan <- err
// return return
// } }
// ws.writeLock.Unlock() ws.conn.SetWriteDeadline(time.Now().Add(ws.IdleTimeout))
// } ws.writeLock.Unlock()
// } // log.Printf("Client %d: Ping OK", ws.id)
}
}

View File

@@ -43,9 +43,11 @@ func handleDownload(responseWriter http.ResponseWriter, request *http.Request) {
server.Broadcast <- req.Link server.Broadcast <- req.Link
} }
func main() { func init() {
log.SetFlags(log.Lmicroseconds) log.SetFlags(log.Lmicroseconds | log.Lshortfile)
}
func main() {
http.HandleFunc("/ws", wsHandler) http.HandleFunc("/ws", wsHandler)
http.HandleFunc("/download", handleDownload) http.HandleFunc("/download", handleDownload)
log.Println("Server starting on :8080") log.Println("Server starting on :8080")

View File

@@ -9,6 +9,7 @@ import (
type WSServer struct { type WSServer struct {
connections map[*WSConnection]bool connections map[*WSConnection]bool
clientId int32
Upgrader websocket.Upgrader Upgrader websocket.Upgrader
Broadcast chan string Broadcast chan string
IdleTimeout time.Duration IdleTimeout time.Duration
@@ -42,9 +43,12 @@ func (server *WSServer) HandleNew(conn *websocket.Conn) {
server.connections[wsconn] = true server.connections[wsconn] = true
go func() { go func() {
<-wsconn.ErrorChan err := <-wsconn.ErrorChan
wsconn.alive = false wsconn.alive = false
close(wsconn.ReadChan)
close(wsconn.WriteChan)
close(wsconn.ErrorChan)
log.Printf("Client %d: disconnected due to %+v, now %d clients", wsconn.id, err, len(server.connections))
delete(server.connections, wsconn) delete(server.connections, wsconn)
log.Printf("Client disconnected, now %d clients", len(server.connections))
}() }()
} }