-
Notifications
You must be signed in to change notification settings - Fork 91
/
agent.go
74 lines (65 loc) · 1.53 KB
/
agent.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
package main
import (
"time"
)
import (
pb "agent/pb"
. "agent/types"
"agent/utils"
)
// PIPELINE #2: agent
// all the packets from handleClient() will be handled
func agent(sess *Session, in chan []byte, out *Buffer) {
defer wg.Done() // will decrease waitgroup by one, useful for manual server shutdown
defer utils.PrintPanicStack()
// init session
sess.MQ = make(chan pb.Game_Frame, 512)
sess.ConnectTime = time.Now()
sess.LastPacketTime = time.Now()
// minute timer
min_timer := time.After(time.Minute)
// cleanup work
defer func() {
close(sess.Die)
if sess.Stream != nil {
sess.Stream.CloseSend()
}
}()
// >> the main message loop <<
// handles 4 types of message:
// 1. from client
// 2. from game service
// 3. timer
// 4. server shutdown signal
for {
select {
case msg, ok := <-in: // packet from network
if !ok {
return
}
sess.PacketCount++
sess.PacketCount1Min++
sess.PacketTime = time.Now()
if result := route(sess, msg); result != nil {
out.send(sess, result)
}
sess.LastPacketTime = sess.PacketTime
case frame := <-sess.MQ: // packets from game
switch frame.Type {
case pb.Game_Message:
out.send(sess, frame.Message)
case pb.Game_Kick:
sess.Flag |= SESS_KICKED_OUT
}
case <-min_timer: // minutes timer
timer_work(sess, out)
min_timer = time.After(time.Minute)
case <-die: // server is shuting down...
sess.Flag |= SESS_KICKED_OUT
}
// see if the player should be kicked out.
if sess.Flag&SESS_KICKED_OUT != 0 {
return
}
}
}