-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
107 lines (91 loc) · 2.17 KB
/
context.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
package gonet
import (
"github.com/flylib/interface/codec"
ilog "github.com/flylib/interface/log"
"reflect"
)
type TransportProtocol string
const (
TCP TransportProtocol = "tcp"
KCP TransportProtocol = "kcp"
UDP TransportProtocol = "udp"
WS TransportProtocol = "websocket"
HTTP TransportProtocol = "http"
QUIC TransportProtocol = "quic"
RPC TransportProtocol = "rpc"
)
type invalidData struct {
}
var zeroData = invalidData{}
type Context struct {
//session manager
sessions *sessionManager
//go routine pool
routines *GoroutinePool
//Message callback processing
eventHandler IEventHandler
maxSessionCount int
//routine pool config
poolCfg poolConfig
//message codec
codec.ICodec
ilog.ILogger
//net package parser
INetPackager
sessionType reflect.Type
}
func NewContext(options ...Option) *Context {
ctx := &Context{
INetPackager: &DefaultNetPackager{},
}
for _, f := range options {
f(ctx)
}
if ctx.ICodec == nil {
panic("nil ICodec")
}
if ctx.ILogger == nil {
panic("nil ILogger")
}
if ctx.sessionType == nil {
panic("nil sessionType")
}
ctx.routines = newGoroutinePool(ctx)
ctx.sessions = newSessionManager(ctx.sessionType)
return ctx
}
// 会话管理
func (c *Context) GetSession(id uint64) (ISession, bool) {
return c.sessions.getAliveSession(id)
}
func (c *Context) GetIdleSession() ISession {
idleSession := c.sessions.getIdleSession()
idleSession.(interface{ Clear() }).Clear()
c.sessions.addAliveSession(idleSession)
return idleSession.(ISession)
}
func (c *Context) RecycleSession(session ISession) {
session.Close()
session.(interface{ Clear() }).Clear()
c.sessions.recycleIdleSession(session)
}
func (c *Context) SessionCount() int32 {
return c.sessions.countAliveSession()
}
func (c *Context) Broadcast(msgId uint32, msg any) {
c.sessions.alive.Range(func(_, item interface{}) bool {
session, ok := item.(ISession)
if ok {
session.Send(msgId, msg)
}
return true
})
}
func (c *Context) GetEventHandler() IEventHandler {
return c.eventHandler
}
// push the message to the routine pool
func (c *Context) PushGlobalMessageQueue(msg IMessage) {
// active defense to avoid too many message
c.routines.queue <- msg
}