server.go
2.41 KB
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
package components
import (
"fmt"
"github.com/golang/protobuf/proto"
"net"
"plugin"
"pro2d/pb"
"pro2d/utils/logger"
"sync"
)
type ActionHandler func (msg IMessage) (int32, proto.Message)
var ActionMap map[pb.ProtoCode]ActionHandler
type Server struct {
IServer
connectionCallback ConnectionCallback
messageCallback MessageCallback
closeCallback CloseCallback
timerCallback TimerCallback
splitter ISplitter
port int
PluginPath string
Clients *sync.Map
}
func NewServer(port int, pluginPath string, splitter ISplitter) *Server {
s := &Server{
splitter: splitter,
port: port,
PluginPath: pluginPath,
Clients: new(sync.Map),
}
return s
}
func (s *Server) GetSplitter() ISplitter {
return s.splitter
}
func (s *Server) GetIConnection(id int) IConnection {
c, ok := s.Clients.Load(id)
if !ok {
return nil
}
return c.(IConnection)
}
func (s *Server) SetConnectionCallback(cb ConnectionCallback) {
s.connectionCallback = cb
}
func (s *Server) SetMessageCallback(cb MessageCallback) {
s.messageCallback = cb
}
func (s *Server) SetCloseCallback(cb CloseCallback) {
s.closeCallback = cb
}
func (s *Server) SetTimerCallback(cb TimerCallback) {
s.timerCallback = cb
}
func (s *Server) newConnection(conn IConnection) {
s.Clients.Store(conn.GetID(), conn)
conn.SetConnectionCallback(s.connectionCallback)
conn.SetCloseCallback(s.removeConnection)
conn.SetMessageCallback(s.messageCallback)
conn.SetTimerCallback(s.timerCallback)
go conn.Start()
}
func (s *Server) removeConnection(conn IConnection) {
s.closeCallback(conn)
s.Clients.Delete(conn.GetID())
}
func (s *Server) LoadPlugin() {
//重新加载
_, err:=plugin.Open(s.PluginPath)
if err != nil {
logger.Error("load plugin err: %v, %s", err, s.PluginPath)
return
}
logger.Debug("load plugin success")
}
func (s *Server) Start() error {
//初始化plugin
//_, err = plugin.Open(conf.GlobalConf.GameConf.PluginPath)
//if err != nil {
// return err
//}
port := fmt.Sprintf(":%d", s.port)
l, err := net.Listen("tcp", port)
if err != nil {
return err
}
//监听端口
logger.Debug("listen on %s\n", port)
id := 0
for {
conn, err := l.Accept()
if err != nil {
return err
}
id++
client := NewConn(id, conn, s)
s.newConnection(client)
}
}
func (s *Server)Stop() {
StopTimer()
s.Clients.Range(func(key, value interface{}) bool {
client := value.(IConnection)
client.Stop()
return true
})
}