This repository has been archived by the owner on May 26, 2021. It is now read-only.
forked from things-go/go-modbus
-
Notifications
You must be signed in to change notification settings - Fork 7
/
tcpserver.go
111 lines (100 loc) · 2.21 KB
/
tcpserver.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
package modbus
import (
"context"
"net"
"sync"
"time"
)
// TCP Default read & write timeout
const (
TCPDefaultReadTimeout = 60 * time.Second
TCPDefaultWriteTimeout = 1 * time.Second
)
// TCPServer modbus tcp server
type TCPServer struct {
mu sync.Mutex
listen net.Listener
wg sync.WaitGroup
cancel context.CancelFunc
readTimeout time.Duration
writeTimeout time.Duration
*serverCommon
logger
}
// NewTCPServer the modbus server listening on "address:port".
func NewTCPServer() *TCPServer {
return &TCPServer{
readTimeout: TCPDefaultReadTimeout,
writeTimeout: TCPDefaultWriteTimeout,
serverCommon: newServerCommon(),
logger: newLogger("modbusTCPServer => "),
}
}
// SetReadTimeout set read timeout
func (sf *TCPServer) SetReadTimeout(t time.Duration) *TCPServer {
sf.readTimeout = t
return sf
}
// SetWriteTimeout set write timeout
func (sf *TCPServer) SetWriteTimeout(t time.Duration) *TCPServer {
sf.writeTimeout = t
return sf
}
// Close close the server until all server close then return
func (sf *TCPServer) Close() error {
sf.mu.Lock()
if sf.listen != nil {
sf.listen.Close()
sf.cancel()
sf.listen = nil
}
sf.mu.Unlock()
sf.wg.Wait()
return nil
}
const minTempDelay = 5 * time.Millisecond
// ListenAndServe listen and server
func (sf *TCPServer) ListenAndServe(addr string) error {
listen, err := net.Listen("tcp", addr)
if err != nil {
return err
}
ctx, cancel := context.WithCancel(context.Background())
sf.mu.Lock()
sf.listen = listen
sf.cancel = cancel
sf.mu.Unlock()
sf.Debug("server started,and listen address: %s", addr)
defer func() {
sf.Close()
sf.Debug("server stopped")
}()
var tempDelay = minTempDelay // how long to sleep on accept failure
for {
conn, err := listen.Accept()
if err != nil {
if ne, ok := err.(net.Error); ok && ne.Temporary() {
tempDelay <<= 1
if max := 1 * time.Second; tempDelay > max {
tempDelay = max
}
time.Sleep(tempDelay)
continue
}
return err
}
tempDelay = minTempDelay
sf.wg.Add(1)
go func() {
sess := &ServerSession{
conn,
sf.readTimeout,
sf.writeTimeout,
sf.serverCommon,
sf.logger,
}
sess.running(ctx)
sf.wg.Done()
}()
}
}