-
Notifications
You must be signed in to change notification settings - Fork 17
/
tserver.go
123 lines (102 loc) · 2.61 KB
/
tserver.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
package turbo
import (
"context"
"github.com/blackbeans/logx"
"net"
"runtime"
"time"
)
//turbo日志
var log = logx.GetLogger("turbo")
type TServer struct {
ctx context.Context
cancel context.CancelFunc
hostport string
keepalive time.Duration
stopChan chan bool
isShutdown bool
onMessage THandler
config *TConfig
codec func() ICodec
}
func NewTServer(hostport string, config *TConfig,
onMessage THandler) *TServer {
runtime.GOMAXPROCS(runtime.NumCPU() + 1)
server := &TServer{
hostport: hostport,
stopChan: make(chan bool, 1),
onMessage: onMessage,
isShutdown: false,
config: config,
keepalive: 5 * time.Minute,
codec: func() ICodec {
return LengthBytesCodec{
MaxFrameLength: MAX_PACKET_BYTES}
}}
server.ctx, server.cancel = context.WithCancel(context.Background())
return server
}
func NewTServerWithCodec(hostport string, config *TConfig, codec func() ICodec,
onMessage THandler) *TServer {
//设置为8个并发
runtime.GOMAXPROCS(runtime.NumCPU() + 1)
server := &TServer{
hostport: hostport,
stopChan: make(chan bool, 1),
onMessage: onMessage,
isShutdown: false,
config: config,
keepalive: 5 * time.Minute,
codec: codec}
server.ctx, server.cancel = context.WithCancel(context.Background())
return server
}
func (self *TServer) ListenAndServer() error {
addr, err := net.ResolveTCPAddr("tcp4", self.hostport)
if nil != err {
log.Errorf("TServer|ADDR|FAIL|%s", self.hostport)
return err
}
listener, err := net.ListenTCP("tcp4", addr)
if nil != err {
log.Errorf("TServer|ListenTCP|FAIL|%v|%s", err, addr)
return err
}
stopListener := &StoppedListener{listener, self.stopChan, make(chan *net.TCPConn), self.keepalive}
//开始服务获取连接
go self.serve(stopListener)
return nil
}
//networkstat
func (self *TServer) NetworkStat() NetworkStat {
return self.config.FlowStat.Stat()
}
//列出来客户端
func (self *TServer) ListClients() []string {
clients := make([]string, 0, 10)
self.config.FlowStat.Clients.Range(func(key, value interface{}) bool {
clients = append(clients, key.(string))
return true
})
return clients
}
func (self *TServer) serve(l *StoppedListener) error {
for !self.isShutdown {
conn, err := l.Accept()
if nil != err {
log.Errorf("TServer|serve|AcceptTCP|FAIL|%s", err)
continue
} else {
//创建remotingClient对象
tclient := NewTClient(self.ctx, conn, self.codec, self.onMessage, self.config)
tclient.Start()
}
}
return nil
}
func (self *TServer) Shutdown() {
self.isShutdown = true
close(self.stopChan)
self.cancel()
log.Infof("TServer|Shutdown...")
}