Rework WS server
This commit is contained in:
50
ws-server/server.go
Normal file
50
ws-server/server.go
Normal 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))
|
||||
}()
|
||||
}
|
Reference in New Issue
Block a user