-
Notifications
You must be signed in to change notification settings - Fork 3
/
send_message.go
53 lines (49 loc) · 1.23 KB
/
send_message.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
/*
* @Author: 时光弧线
* @Date: 2017-12-30 11:55:38
* @Last Modified by: 时光弧线
* @Last Modified time: 2017-12-30 13:14:28
*/
package tcplibrary
import (
"errors"
)
/* 公共发送数据函数 */
// SendMessageToClients 发送数据给指定客户端
// 返回值,第一个值为发送成功几个连接
// 只有服务端可调用
func (t *TCPLibrary) SendMessageToClients(v interface{}, clientIDs ...string) (sendCount int, err error) {
if t.isServer == false {
return 0, errors.New("客户端不允许调用此函数")
}
for _, vv := range clientIDs {
if val, ok := t.clients.Load(vv); ok == true {
if conn, ok := val.(*Conn); ok == true {
_, err = conn.SendMessage(v)
if err == nil {
sendCount++
}
}
}
}
return sendCount, err
}
// SendMessageToAll 发送给所有客户端
// 只有服务端可调用
func (t *TCPLibrary) SendMessageToAll(v interface{}) (int, error) {
if t.isServer == false {
return 0, errors.New("客户端不允许调用此函数")
}
sendCount := 0
t.clients.Range(func(key, val interface{}) bool {
if conn, ok := val.(*Conn); ok == true {
_, err := conn.SendMessage(v)
if err != nil {
return true
}
sendCount++
}
return true
})
return sendCount, nil
}