/
udp.go
88 lines (75 loc) · 1.83 KB
/
udp.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
package model
import (
"fmt"
"github.com/mangenotwork/extras/common/utils"
"net"
)
type UdpClient struct {
Conn *net.UDPAddr
UserID string // 用户id唯一的
IP string // 当前连接的ip
DeviceID string // 当前连接的设备id
Source string // 设备类型
UDPListener *net.UDPConn
}
func (udp *UdpClient) GetIP() string {
return udp.IP
}
func (udp *UdpClient) Send(msg []byte) {
_,_=udp.UDPListener.WriteToUDP(msg, udp.Conn)
}
func (udp *UdpClient) GetConn() *net.UDPAddr {
return udp.Conn
}
// 使用哈希表存储
type udpNode struct {
Data map[string]*UdpClient // UserID 用户id作为key
}
type UdpHashTable struct {
Table map[int64]*udpNode // UserID 用户id 哈希后作为key
Size int64
}
func (table *UdpHashTable) hashFunction(uid string) int64 {
uidInt := utils.Str2Int64(uid)
return uidInt % table.Size
}
func (table *UdpHashTable) Insert(value *UdpClient){
h := table.hashFunction(value.UserID)
element, ok := table.Table[h]
if !ok {
element = &udpNode{
Data: make(map[string]*UdpClient),
}
table.Table[h] = element
}
element.Data[value.UserID] = value
}
func (table *UdpHashTable) Get(uid string) (date *UdpClient, err error){
if t, ok := table.Table[table.hashFunction(uid)]; ok {
if client, ok := t.Data[uid]; ok {
return client, nil
}
}
return nil, fmt.Errorf("not fond")
}
func (table *UdpHashTable) Del(value *UdpClient) {
h := table.hashFunction(value.UserID)
element, ok := table.Table[h]
if ok {
delete(element.Data, value.UserID)
}
}
func InitUdpConnTable() *UdpHashTable {
table := make(map[int64]*udpNode, HashSize)
return &UdpHashTable{Table: table, Size: int64(HashSize)}
}
func udpTraverse(hash *TcpHashTable) {
for k := range hash.Table {
if hash.Table[k] != nil {
for k,v := range hash.Table[k].Data {
fmt.Printf("%v (%v) -> ", k, v)
}
}
fmt.Println()
}
}