-
Notifications
You must be signed in to change notification settings - Fork 0
/
hub.go
executable file
·56 lines (52 loc) · 1.32 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
package main
import (
"encoding/json"
"too-white/log"
)
type Server struct {
clients map[*Client]bool
broadcast chan *Content
register chan *Client
unregister chan *Client
}
func newServer() *Server {
return &Server{
broadcast: make(chan *Content),
register: make(chan *Client),
unregister: make(chan *Client),
clients: make(map[*Client]bool),
}
}
func (serv *Server) run() {
for {
log.NewLog("hub.go-26:第一个goroutine for 循环阻塞", "")
select {
case client := <-serv.register:
serv.clients[client] = true
log.NewLog("hub.go-30:把客户端放在线程池里,第二步", serv.clients)
case client := <-serv.unregister:
log.NewLog("hub.go-32:用户离线", serv.clients)
if _, ok := serv.clients[client]; ok {
delete(serv.clients, client)
close(client.send)
// db.UserOffLine(client.uid)
}
case content := <-serv.broadcast:
// 根据content传过来的需要广播的target来遍历广播
log.NewLog("hub.go-40:开始广播了!!!", "")
message, _ := json.Marshal(content.Data)
if content.Target != nil {
for _, client := range content.Target {
if _, ok := serv.clients[client]; ok {
select {
case client.send <- message:
default:
close(client.send)
delete(serv.clients, client)
}
}
}
}
}
}
}