-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcp.go
53 lines (44 loc) · 935 Bytes
/
tcp.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
package main
import (
"net"
"go.uber.org/zap"
)
// TCP client and server
type TcpServer struct {
lnr net.Listener
addr string
}
type TcpClient struct {
conn net.TCPConn
addr string
}
func (c *TcpClient) Connect() (DataChannel, error) {
cc, err := net.Dial("tcp", c.addr)
if err != nil {
lg.Debug("TCP connection failed")
return nil, err
} else {
lg.Debug("TCP connected", zap.String("remote", cc.RemoteAddr().String()))
}
ctcp, _ := cc.(*net.TCPConn)
return ctcp, err
}
func (c *TcpClient) Close() error {
return c.conn.Close()
}
func (s *TcpServer) Listen() error {
var err error
s.lnr, err = net.Listen("tcp", s.addr)
return err
}
func (s *TcpServer) Accept(dcs chan<- interface{}) error {
dc, err := s.lnr.Accept()
if err == nil {
lg.Debug("New connection ", zap.String("remote", dc.RemoteAddr().String()))
dcs <- dc
}
return err
}
func (s *TcpServer) Close() error {
return s.lnr.Close()
}