-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
86 lines (72 loc) · 1.59 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"fmt"
"sync"
"time"
"github.com/gorilla/websocket"
)
type Server struct {
rooms map[string]*Room
mux sync.Mutex
}
func newServer() *Server {
return &Server{
rooms: make(map[string]*Room),
}
}
func (s *Server) livenessChecker(r *Room) {
defer func() {
r.control <- &RoomControl{msg: disconnectCommand}
//TODO: check if it always deletes all clients before removing a room
s.mux.Lock()
delete(s.rooms, r.roomID)
s.mux.Unlock()
}()
for {
time.Sleep(livenessCheckTime)
if time.Now().After(r.readTimeout()) {
fmt.Println("livenessChecker - timeout")
break
}
}
}
func (s *Server) roomsCount() int {
s.mux.Lock()
defer s.mux.Unlock()
return len(s.rooms)
}
func (s *Server) addRoom(room *Room) {
s.mux.Lock()
fmt.Printf("adding new room: %+v\n", room.roomID)
s.rooms[room.roomID] = room
go s.livenessChecker(room)
s.mux.Unlock()
}
func (s *Server) getRoomByID(roomID string) *Room {
var room *Room
s.mux.Lock()
room = s.rooms[roomID]
s.mux.Unlock()
if room == nil {
room = newRoom(roomID)
s.addRoom(room)
}
return room
}
func (s *Server) addClientToRoom(room *Room, conn *websocket.Conn) {
room.addClient(conn)
room.extendTimeout()
}
func (s *Server) addClientToRoomByID(roomID string, conn *websocket.Conn) {
room := s.getRoomByID(roomID)
s.addClientToRoom(room, conn)
}
func (s *Server) broadcastToRoomByID(roomID string, msg string) {
room := server.getRoomByID(roomID)
room.broadcast <- []byte(msg)
room.extendTimeout()
}
func (s *Server) pingRoomByID(roomID string) {
room := server.getRoomByID(roomID)
room.extendTimeout()
}