forked from tbrandon/mbserver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
servetcp.go
73 lines (64 loc) · 1.56 KB
/
servetcp.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
package mbserver
import (
"crypto/tls"
"io"
"log"
"net"
"strings"
)
func (s *Server) accept(listen net.Listener) error {
for {
conn, err := listen.Accept()
if err != nil {
if strings.Contains(err.Error(), "use of closed network connection") {
return nil
}
log.Printf("Unable to accept connections: %#v\n", err)
return err
}
go func(conn net.Conn) {
defer conn.Close()
for {
packet := make([]byte, 512)
bytesRead, err := conn.Read(packet)
if err != nil {
if err != io.EOF {
log.Printf("read error %v\n", err)
}
return
}
// Set the length of the packet to the number of read bytes.
packet = packet[:bytesRead]
frame, err := NewTCPFrame(packet)
if err != nil {
log.Printf("bad packet error %v\n", err)
return
}
request := &Request{conn, frame}
s.requestChan <- request
}
}(conn)
}
}
// ListenTCP starts the Modbus server listening on "address:port".
func (s *Server) ListenTCP(addressPort string) (err error) {
listen, err := net.Listen("tcp", addressPort)
if err != nil {
log.Printf("Failed to Listen: %v\n", err)
return err
}
s.listeners = append(s.listeners, listen)
go s.accept(listen)
return err
}
// ListenTLS starts the Modbus server listening on "address:port".
func (s *Server) ListenTLS(addressPort string, config *tls.Config) (err error) {
listen, err := tls.Listen("tcp", addressPort, config)
if err != nil {
log.Printf("Failed to Listen on TLS: %v\n", err)
return err
}
s.listeners = append(s.listeners, listen)
go s.accept(listen)
return err
}