-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
56 lines (48 loc) · 974 Bytes
/
client.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 session
import (
"github.com/gorilla/websocket"
"github.com/micro/go-micro/v2/util/log"
"sync"
)
//Client Connection
type Client struct {
userID string
conns map[*websocket.Conn]*Connection
}
func (c *Client) add(conn *websocket.Conn) {
_, ok := c.conns[conn]
if ok {
return
}
c.conns[conn] = &Connection{
conn: conn,
}
}
func (c *Client) delete(conn *websocket.Conn) {
delete(c.conns, conn)
}
func (c *Client) sendMessage(msg interface{}) {
for _, conn := range c.conns {
err := conn.WriteJSON(msg)
if err != nil {
log.Errorf("conn.WriteJSON error:%v", err)
}
}
}
//parameters
var (
clients = make(map[string]*Client)
lock sync.RWMutex
)
//SendMessage To User..
func SendMessage(msg interface{}, userIDs []string) {
lock.RLock()
for _, userID := range userIDs {
client, exist := clients[userID]
if exist {
log.Infof("push message(data:%s), user(%s)", msg, userID)
client.sendMessage(msg)
}
}
lock.RUnlock()
}