Files
youtube-downloader/ws-server/server.go
2024-06-27 10:42:17 +02:00

51 lines
1.1 KiB
Go

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