-
Notifications
You must be signed in to change notification settings - Fork 4
/
tcp_client.go
85 lines (65 loc) · 1.46 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
package tcp_client
import (
"bufio"
"net"
)
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() {
conexao, err := net.Dial("tcp", self.Address)
if err != nil {
self.onErrorCallback(err)
} else {
defer conexao.Close()
self.Conn = conexao
self.Connected = true
self.onOpenCallback()
self.read()
}
}
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
}