-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathnet_manager.go
261 lines (218 loc) · 6.07 KB
/
net_manager.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
package litenetlib
import (
"log"
"net"
"sync"
"errors"
"github.com/emirpasic/gods/maps/hashmap"
"github.com/enriquebris/goconcurrentqueue"
)
type NetManager struct {
config *NetManagerConfig
listener INetListener
socket *NetSocket
stats *NetStatistics
peers *hashmap.Map
peersMutex sync.Mutex
connectRequests *hashmap.Map
connectRequestsMutex sync.Mutex
netEventsQueue *goconcurrentqueue.FIFO
netEventsQueueMutex sync.Mutex
unsyncedEvents bool
packetsReceived int
bytesReceived int
}
type NetManagerConfig struct {
AddrV4 string
PortV4 int
AddrV6 string
PortV6 int
StatsEnabled bool
BroadcastReceiveEnabled bool
UnconnectedMessagesEnabled bool
NatPunchEnabled bool
}
func (netManager *NetManager) Start() error {
log.Printf("Starting net manager...")
if netManager.config.AddrV4 != "" && netManager.config.PortV4 != 0 {
err := netManager.socket.BindV4(netManager.config.AddrV4, netManager.config.PortV4)
if err != nil {
return err
}
}
if netManager.config.AddrV6 != "" && netManager.config.PortV6 != 0 {
err := netManager.socket.BindV6(netManager.config.AddrV6, netManager.config.PortV6)
if err != nil {
return err
}
}
if !netManager.socket.IsListening() {
return errors.New("No valid socket listeners have been setup.")
}
return nil
}
func (netManager *NetManager) Stop() {
if netManager.socket == nil {
return
}
log.Printf("Stopping net manager...")
netManager.socket.Close()
}
func (netManager *NetManager) PollEvents() {
if netManager.unsyncedEvents {
return
}
netManager.netEventsQueueMutex.Lock()
defer netManager.netEventsQueueMutex.Unlock()
// log.Println("PollEvents()")
for {
if netManager.netEventsQueue.GetLen() == 0 {
// log.Println("Queue is empty")
return
} else {
eventInterface, err := netManager.netEventsQueue.Dequeue()
if err != nil {
return
}
netManager.processEvent(eventInterface.(*NetEvent))
}
}
}
func (netManager *NetManager) Stats() *NetStatistics {
return netManager.stats
}
func (netManager *NetManager) processEvent(event *NetEvent) {
log.Println("processEvent")
}
func (netManager *NetManager) dataReceived(numBytes int, buf []byte, addr *net.UDPAddr) {
if buf[0] == NetPacketProperty_Empty {
return
}
packet, err := NewNetPacket(buf, 0, numBytes)
if err != nil {
return
}
if netManager.config.StatsEnabled {
stats := netManager.stats
stats.PacketsReceived++;
stats.BytesReceived += int64(packet.Length());
log.Printf("Packets received: %d", stats.PacketsReceived)
log.Printf("Bytes received: %d", stats.BytesReceived)
}
log.Printf("Packet length: %d", packet.Length())
switch packet.Property() {
case NetPacketProperty_ConnectRequest:
// todo:
// if (NetConnectRequestPacket.GetProtocolId(packet) != NetConstants.ProtocolId)
// SendRawAndRecycle(NetPacketPool.GetWithProperty(PacketProperty.InvalidProtocol), remoteEndPoint);
break
case NetPacketProperty_Broadcast:
if !netManager.config.BroadcastReceiveEnabled {
return
}
netManager.newNetEvent(&NetEvent{
eventType: NetEventType_Broadcast,
addr: addr,
packet: packet,
})
break
case NetPacketProperty_UnconnectedMessage:
if !netManager.config.UnconnectedMessagesEnabled {
return
}
netManager.newNetEvent(&NetEvent{
eventType: NetEventType_ReceiveUnconnected,
addr: addr,
packet: packet,
})
break
case NetPacketProperty_NatMessage:
if !netManager.config.NatPunchEnabled {
return
}
// todo:
// NatPunchModule.ProcessMessage(remoteEndPoint, packet);
break
}
netManager.peersMutex.Lock()
peerInterface, peerFound := netManager.peers.Get(addr.String())
netManager.peersMutex.Unlock()
var peer *NetPeer
if peerFound {
peer = peerInterface.(*NetPeer)
}
switch packet.Property() {
case NetPacketProperty_ConnectRequest:
netManager.processConnectRequest(peer, addr, packet);
break
case NetPacketProperty_PeerNotFound:
log.Println("PeerNotFound")
break
case NetPacketProperty_InvalidProtocol:
log.Println("InvalidProtocol")
break
case NetPacketProperty_Disconnect:
log.Println("Disconnect")
break
case NetPacketProperty_ConnectAccept:
log.Println("ConnectAccept")
break
default:
if peerFound {
peer.ProcessPacket(packet)
} else {
// todo:
// SendRawAndRecycle(NetPacketPool.GetWithProperty(PacketProperty.PeerNotFound), remoteEndPoint);
}
break
}
}
func (netManager *NetManager) newNetEvent(event *NetEvent) {
netManager.netEventsQueueMutex.Lock()
netManager.netEventsQueue.Enqueue(event)
netManager.netEventsQueueMutex.Unlock()
}
func (netManager *NetManager) processConnectRequest(peer *NetPeer, addr *net.UDPAddr, packet *NetPacket) {
if peer != nil {
}
netManager.connectRequestsMutex.Lock()
connectRequestInterface, connectRequestFound := netManager.connectRequests.Get(addr.String())
netManager.connectRequestsMutex.Unlock()
var connectRequest *ConnectRequest
if connectRequestFound {
connectRequest = connectRequestInterface.(*ConnectRequest)
connectRequest.UpdateRequest(packet)
} else {
netManager.connectRequests.Put(addr.String(), &ConnectRequest{
addr: addr,
packet: packet,
})
}
netManager.newNetEvent(&NetEvent{
eventType: NetEventType_ConnectionRequest,
connectRequest: connectRequest,
})
}
type netManagerSocketListener struct {
netManager *NetManager
}
func (listener *netManagerSocketListener) OnMessageReceived(numBytes int, buf []byte, addr *net.UDPAddr) {
listener.netManager.dataReceived(numBytes, buf, addr)
}
func NewNetManager(config *NetManagerConfig, listener INetListener) *NetManager {
netManager := &NetManager{
config: config,
listener: listener,
peers: hashmap.New(),
connectRequests: hashmap.New(),
netEventsQueue: goconcurrentqueue.NewFIFO(),
unsyncedEvents: false,
}
netManager.socket = NewNetSocket(&netManagerSocketListener{
netManager: netManager,
})
if config.StatsEnabled {
netManager.stats = NewNetStatistics()
}
return netManager
}