Rework WS server

This commit is contained in:
2024-06-27 10:42:17 +02:00
parent c930aeb737
commit 4acb89cdb1
3 changed files with 152 additions and 117 deletions

50
ws-server/server.go Normal file
View File

@@ -0,0 +1,50 @@
package main
import (
"log"
"time"
"github.com/gorilla/websocket"
)
type WSServer struct {
connections map[*WSConnection]bool
Upgrader websocket.Upgrader
Broadcast chan string
IdleTimeout time.Duration
PingInterval time.Duration
}
func New(timeout time.Duration) *WSServer {
server := &WSServer{
connections: make(map[*WSConnection]bool),
Upgrader: websocket.Upgrader{},
Broadcast: make(chan string, 128),
IdleTimeout: timeout,
PingInterval: timeout / 2,
}
go func() {
for {
msg := <-server.Broadcast
for conn := range server.connections {
conn.WriteChan <- msg
}
}
}()
return server
}
func (server *WSServer) HandleNew(conn *websocket.Conn) {
log.Printf("Client connected, now %d clients", len(server.connections)+1)
wsconn := NewConn(conn, server)
go wsconn.Open()
server.connections[wsconn] = true
go func() {
<-wsconn.ErrorChan
wsconn.alive = false
delete(server.connections, wsconn)
log.Printf("Client disconnected, now %d clients", len(server.connections))
}()
}