-
Notifications
You must be signed in to change notification settings - Fork 1
/
rpc_server.go
108 lines (88 loc) · 1.84 KB
/
rpc_server.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
package network
import (
"github.com/phuhao00/spoor/logger"
"net"
"net/rpc"
"runtime/debug"
"sync"
"time"
)
type RpcServer struct {
Addr string
ln *net.TCPListener
wgLn sync.WaitGroup
}
func (srv *RpcServer) Init(addr string) {
srv.Addr = addr
tcpAddr, err := net.ResolveTCPAddr("tcp4", srv.Addr)
if err != nil {
logger.Error("[net] addr resolve error", tcpAddr, err)
return
}
ln, err := net.ListenTCP("tcp", tcpAddr)
if err != nil {
logger.Error("%v", err)
return
}
srv.ln = ln
logger.Info("RpcServer Listen %s", srv.ln.Addr().String())
}
func (srv *RpcServer) Run() {
defer func() {
if err := recover(); err != nil {
logger.Error("[net] panic", err, "\n", string(debug.Stack()))
}
}()
srv.wgLn.Add(1)
defer srv.wgLn.Done()
var tempDelay time.Duration
for {
conn, err := srv.ln.AcceptTCP()
if err != nil {
if ne, ok := err.(net.Error); ok && ne.Temporary() {
if tempDelay == 0 {
tempDelay = 5 * time.Millisecond
} else {
tempDelay *= 2
}
if max := 1 * time.Second; tempDelay > max {
tempDelay = max
}
logger.Warn("accept error: %v; retrying in %v", err, tempDelay)
time.Sleep(tempDelay)
continue
}
return
}
tempDelay = 0
err = conn.SetKeepAlive(true)
if err != nil {
logger.Error(err.Error())
}
err = conn.SetKeepAlivePeriod(1 * time.Minute)
if err != nil {
logger.Error(err.Error())
}
err = conn.SetNoDelay(true)
if err != nil {
logger.Error(err.Error())
}
err = conn.SetWriteBuffer(128 * 1024)
if err != nil {
logger.Error(err.Error())
}
err = conn.SetReadBuffer(128 * 1024)
if err != nil {
logger.Error(err.Error())
}
go rpc.ServeConn(conn)
logger.Debug("accept a rpc conn")
}
}
func (srv *RpcServer) Close() {
err := srv.ln.Close()
if err != nil {
logger.Error(err.Error())
}
srv.wgLn.Wait()
}