-
Notifications
You must be signed in to change notification settings - Fork 4
/
connection.go
162 lines (140 loc) · 3.1 KB
/
connection.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
package rpckit
import (
"bytes"
"errors"
"fmt"
"io"
"net"
"sync/atomic"
)
type ConnectionHandler func(c *Connection)
type MessageHandler func(c *Connection, msg *Message)
type DisconnectedHandler func(c *Connection, err error)
// connId is a runtime connection counter
var connId uint64
type Connection struct {
id uint64
closed int32
conn net.Conn
onMessage MessageHandler
onDisconnect DisconnectedHandler
Data interface{}
}
func NewConnection(network, address string, onMessage MessageHandler, onDisconnect DisconnectedHandler) (*Connection, error) {
conn, err := net.Dial(network, address)
if err != nil {
return nil, err
}
return connected(conn, onMessage, onDisconnect), nil
}
func connected(conn net.Conn, onMessage MessageHandler, onDisconnect DisconnectedHandler) *Connection {
c := &Connection{
id: atomic.AddUint64(&connId, 1),
closed: 0,
conn: conn,
onMessage: onMessage,
onDisconnect: onDisconnect,
}
go c.readLoop()
return c
}
func (c *Connection) RemoteAddr() net.Addr {
return c.conn.RemoteAddr()
}
func (c *Connection) readLoop() {
buf := make([]byte, 0, 512)
off := 0
minRead := 256
// kill bad connections
defer func() {
if bad := recover(); bad != nil {
if err, ok := bad.(error); ok {
c.end(err)
} else {
c.end(fmt.Errorf("unhandled: %v", bad))
}
}
}()
for {
// read from the connection
if off >= len(buf) {
buf = buf[:0]
off = 0
}
if free := cap(buf) - len(buf); free < minRead {
//fmt.Println("grow")
// not enough space at end
newBuf := buf
if off+free < minRead {
// not enough space using beginning of buffer;
// double buffer capacity
newBuf = makeSlice(2*cap(buf) + minRead)
}
copy(newBuf, buf[off:])
buf = newBuf[:len(buf)-off]
off = 0
}
m, err := c.conn.Read(buf[len(buf):cap(buf)])
buf = buf[0 : len(buf)+m]
if err == io.EOF {
c.end(nil)
return
}
if err != nil {
c.end(err)
return
}
for {
msg, length := MessageFromBytes(buf[off:])
if msg != nil {
off += length
c.onMessage(c, msg)
} else {
break
}
}
}
}
var ErrMsgNotFullySent = errors.New("all the message bytes were not sent - perhaps the message is too large")
func (c *Connection) Write(buf []byte) (int, error) {
return c.conn.Write(buf)
}
func (c *Connection) Send(msg *Message) error {
bytes := msg.Bytes()
n, err := c.conn.Write(bytes)
if err != nil {
return err
}
if n != len(bytes) {
return ErrMsgNotFullySent
}
return nil
}
// Close closes the connection
func (c *Connection) Close() error {
c.end(nil)
return nil
}
// end will only be called once
func (c *Connection) end(err error) {
if atomic.CompareAndSwapInt32(&c.closed, 0, 1) {
c.conn.Close()
d := c.onDisconnect
if d != nil {
c.onDisconnect = nil
d(c, err)
}
}
}
func (c *Connection) String() string {
return fmt.Sprintf("Connection(%d)", atomic.LoadUint64(&c.id))
}
func makeSlice(n int) []byte {
// If the make fails, give a known error.
defer func() {
if recover() != nil {
panic(bytes.ErrTooLarge)
}
}()
return make([]byte, n)
}