-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathhub.go
99 lines (80 loc) · 1.95 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"encoding/json"
"log"
"sync"
)
// hub maintains the set of active clients and broadcasts messages to the
// clients.
type Hub struct {
// Registered clients.
//clients map[*Client]bool
clients sync.Map
// Inbound messages from the clients.
broadcast chan []byte
// Register requests from the clients.
register chan *Client
// Unregister requests from clients.
unregister chan *Client
//count of client
ClientNum uint16
}
func newHub() *Hub {
return &Hub{
broadcast: make(chan []byte),
register: make(chan *Client),
unregister: make(chan *Client),
}
}
// send json object to a client with peerId
func (this *Hub) sendJsonToClient(peerId string, value interface{}) {
b, err := json.Marshal(value)
if err != nil {
log.Println(err)
return
}
client, ok := this.clients.Load(peerId)
if !ok {
//log.Printf("sendJsonToClient error")
return
}
if err := client.(*Client).sendMessage(b); err != nil {
log.Println(err)
}
//if err := client.(*Client).conn.WriteJSON(value); err != nil {
// //logrus.Errorf("[Client.jsonResponse] sendMessage err: %s", err.Error())
//}
}
func (this *Hub) run() {
for {
select {
case client := <-this.register:
this.doRegister(client)
case client := <-this.unregister:
this.doUnregister(client)
}
}
}
func (this *Hub) doRegister(client *Client) {
// logrus.Debugf("[Hub.doRegister] %s", client.id)
if client.PeerId != "" {
this.clients.Store(client.PeerId, client)
this.ClientNum ++
}
}
func (this *Hub) doUnregister(client *Client) {
// logrus.Debugf("[Hub.doUnregister] %s", client.id)
if client.PeerId == "" {
return
}
_, ok := this.clients.Load(client.PeerId)
if ok {
//delRecordCh <- client.id
this.clients.Delete(client.PeerId)
close(client.send)
this.ClientNum --
}
}