-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtcp_client.go
101 lines (88 loc) · 2.11 KB
/
tcp_client.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
package edgerouter
import (
"errors"
"fmt"
"net"
)
type TcpClient struct {
ctl Controller
Port int
conns map[string]*net.TCPConn
}
func (c *TcpClient) Init() {
c.conns = make(map[string]*net.TCPConn)
}
func (c *TcpClient) PacketReceived(bts []byte, conn *net.TCPConn) int {
return c.ctl.OnReceived(bts, conn)
}
func (c *TcpClient) SetController(ctrl Controller) {
c.ctl = ctrl
}
func (c *TcpClient) Connect(to string) error {
if addr, err := net.ResolveTCPAddr("tcp", to); err == nil {
var conn *net.TCPConn
var ok bool
if conn, ok = c.conns[addr.String()]; !ok {
var localPort *net.TCPAddr
if c.Port != 0 {
localPort, _ = net.ResolveTCPAddr("tcp", fmt.Sprintf(":%d", c.Port))
}
if conn, err = net.DialTCP("tcp", localPort, addr); err == nil {
go handleTcpConn(conn, c)
c.conns[addr.String()] = conn
}
}
return err
} else {
return err
}
}
var NoSuchConnection = errors.New("no such connection")
func (c *TcpClient) GetConn(to string, unexceptedConns []net.Conn) (conn net.Conn, err error) {
var addr *net.TCPAddr
if to == "any" {
OUTER:
for _, conn := range c.conns {
for _, unexcepted := range unexceptedConns {
if conn == unexcepted {
continue OUTER
}
}
return conn, nil
}
return nil, NoSuchConnection
}
if addr, err = net.ResolveTCPAddr("tcp", to); err == nil {
var ok bool
if conn, ok = c.conns[addr.String()]; ok {
} else {
err = NoSuchConnection
}
}
return
}
func (c *TcpClient) Close(toDel *net.TCPConn) {
c.DeleteConn(toDel)
}
//TODO client should reconnect to server
func (c *TcpClient) DeleteConn(toDel net.Conn) {
for key, conn := range c.conns {
if conn == toDel {
delete(c.conns, key)
}
}
}
// func (c *TcpClient) Send(msg *BytesMessage, conn net.Conn) (err error) {
// var addr *net.TCPAddr
// if addr, err = net.ResolveTCPAddr("tcp", msg.To); err == nil {
// if conn, ok := c.conns[addr.String()]; ok {
// _, err = conn.Write(msg.Message)
// } else {
// err = errors.New("no such connection")
// }
// }
// return err
// }
func (c *TcpClient) String() string {
return fmt.Sprintf("tcp client(%p)", c)
}