-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconn.go
100 lines (77 loc) · 1.52 KB
/
conn.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
package sockit
import (
"encoding/hex"
"fmt"
"io"
"net"
"sync"
"sync/atomic"
)
type Conn interface {
// LocalAddr returns the local network address.
LocalAddr() net.Addr
// RemoteAddr returns the remote network address.
RemoteAddr() net.Addr
SendPacket(p Packet) error
ReadPacket() (Packet, error)
Close() error
}
type conn struct {
rdLock *sync.Mutex
wrLock *sync.Mutex
net.Conn
codec Codec
closed int32
}
var _ Conn = (*conn)(nil)
func newConn(c net.Conn, codec Codec) *conn {
return &conn{
rdLock: &sync.Mutex{},
wrLock: &sync.Mutex{},
Conn: c,
codec: codec,
closed: 0,
}
}
func (c *conn) Close() error {
if atomic.CompareAndSwapInt32(&c.closed, 0, 1) {
return c.Conn.Close()
}
return nil
}
func (c *conn) SendPacket(p Packet) error {
c.wrLock.Lock()
defer c.wrLock.Unlock()
var wr io.Writer = c.Conn
if DebugReadSend {
wr = debugWriter{c.Conn}
}
return c.codec.Write(wr, p)
}
func (c *conn) ReadPacket() (Packet, error) {
c.rdLock.Lock()
defer c.rdLock.Unlock()
var rd io.Reader = c.Conn
if DebugReadSend {
rd = debugReader{c}
}
return c.codec.Read(rd)
}
var DebugReadSend = false
type debugWriter struct {
w io.Writer
}
func (dw debugWriter) Write(p []byte) (int, error) {
n, err := dw.w.Write(p)
fmt.Println("write data:", p[:n])
fmt.Println("write data hex:", hex.EncodeToString(p[:n]))
return n, err
}
type debugReader struct {
rd io.Reader
}
func (r debugReader) Read(p []byte) (int, error) {
n, err := r.rd.Read(p)
fmt.Println("read data:", p[:n])
return n, err
}