forked from WesleiRamos/tcp_client
/
tcp_client.go
103 lines (81 loc) · 1.79 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
102
103
package tcp_client
import (
"bufio"
"net"
"golang.org/x/net/proxy"
)
type Connection struct {
onOpenCallback func()
onMessageCallback func(message []byte)
onErrorCallback func(err error)
Conn net.Conn
Address string
Connected bool
}
func (self *Connection) OnOpen(f func()) {
self.onOpenCallback = f
}
func (self *Connection) OnMessage(f func(message []byte)) {
self.onMessageCallback = f
}
func (self *Connection) OnError(f func(err error)) {
self.onErrorCallback = f
}
func (self *Connection) Close() {
self.Conn.Close()
}
func (self *Connection) Write(message []byte) {
self.Conn.Write(message)
}
func (self *Connection) WriteString(message string) {
self.Conn.Write([]byte(message))
}
func (self *Connection) Listen(addr string, auth *proxy.Auth) error {
var conexao net.Conn
var err error
if addr != "" {
socks5, err := proxy.SOCKS5("tcp", addr, auth, proxy.Direct)
if err != nil {
return err
}
conexao, err = socks5.Dial("tcp", self.Address)
}else {
conexao, err = net.Dial("tcp", self.Address)
}
if err != nil {
self.onErrorCallback(err)
} else {
defer func() {
if conexao != nil {
conexao.Close()
}
}()
self.Conn = conexao
self.Connected = true
self.onOpenCallback()
self.read()
}
return nil
}
func (self *Connection) read() {
reader := bufio.NewReader(self.Conn)
for {
buf := make([]byte, 1024)
num, err := reader.Read(buf)
if err != nil {
self.Close()
self.onErrorCallback(err)
return
}
mensagem := make([]byte, num)
copy(mensagem, buf)
self.onMessageCallback(mensagem)
}
}
func New(address string) *Connection {
conexao := &Connection{Address: address, Connected: false}
conexao.OnOpen(func() {})
conexao.OnError(func(err error) {})
conexao.OnMessage(func(message []byte) {})
return conexao
}