-
Notifications
You must be signed in to change notification settings - Fork 0
/
hub.go
84 lines (70 loc) · 1.65 KB
/
hub.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
package main
import (
"fmt"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader {
CheckOrigin: func(r *http.Request) bool { return true },
}
// Hub
type Hub struct {
clientList []*Client
register chan *Client
unregister chan *Client
}
func newHub() *Hub {
return &Hub {
clientList: make([]*Client, 0),
register: make(chan *Client),
unregister: make(chan *Client),
}
}
func (hub *Hub) handler(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if(err != nil) {
fmt.Printf("Error occured: %s", err)
return
}
hub.register <- newClient(hub, conn)
}
func (hub *Hub) broadcast(msg string, ignoreClient *Client) {
for _, client := range hub.clientList {
if(client == ignoreClient) {
continue
}
client.socket.WriteMessage(websocket.TextMessage, []byte(msg))
}
}
func (hub *Hub) onConnect(client *Client) {
fmt.Println("On new connect")
hub.broadcast("new client is coming in", nil)
hub.clientList = append(hub.clientList, client)
}
func (hub *Hub) onDisconnect(clientLeave *Client) {
index := -1
for i, client := range hub.clientList {
if(client.id != clientLeave.id) {
continue
}
index = i
break
}
copy(hub.clientList[index:], hub.clientList[index+1:])
hub.clientList[len(hub.clientList) - 1] = nil
hub.clientList = hub.clientList[:len(hub.clientList) - 1]
hub.broadcast("old client is leave", nil)
}
func (hub *Hub) onMessage(msg []byte, client *Client) {
hub.broadcast(string(msg), client)
}
func (hub *Hub) run() {
for {
select {
case client := <- hub.register:
hub.onConnect(client)
case client := <- hub.unregister:
hub.onDisconnect(client)
}
}
}