-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconn.go
145 lines (115 loc) · 2.44 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
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
package wstcp
import (
"bytes"
"io"
"github.com/gobwas/ws"
"github.com/gobwas/ws/wsutil"
)
// WSTCP implements io.ReadWriteCloser
type WSTCP struct {
conn io.ReadWriteCloser
firstBytes []byte
remaining int
wsReader *wsutil.Reader
wsWriter *wsutil.Writer
}
// New wraps incoming connection in WSTCP
func New(conn io.ReadWriteCloser) (*WSTCP, error) {
out := &WSTCP{
conn: conn,
firstBytes: make([]byte, 3),
}
_, err := io.ReadFull(conn, out.firstBytes)
if err != nil {
return nil, err
}
if bytes.Equal(bytes.ToLower(out.firstBytes), []byte("get")) {
_, err = ws.Upgrade(out)
if err != nil {
return nil, err
}
state := ws.StateServerSide
out.wsReader = &wsutil.Reader{
Source: conn,
State: state,
CheckUTF8: true,
OnIntermediate: wsutil.ControlFrameHandler(conn, state),
}
out.wsWriter = wsutil.NewWriter(conn, state, 0)
}
return out, nil
}
func (c *WSTCP) Read(b []byte) (int, error) {
if c.wsReader == nil {
return c.read(b)
}
if c.remaining != 0 {
return c.readWS(b, c.remaining)
}
h, err := c.wsReader.NextFrame()
if err != nil {
return 0, err
}
if h.OpCode.IsControl() {
if !c.wsReader.State.Fragmented() {
err := c.wsReader.OnIntermediate(h, c.wsReader)
if _, isClosed := err.(wsutil.ClosedError); isClosed {
return 0, io.EOF
}
if err != nil {
return 0, err
}
}
return c.Read(b)
}
if h.OpCode == ws.OpText || h.OpCode == ws.OpBinary {
c.wsWriter.Reset(c.conn, c.wsReader.State, h.OpCode)
}
n, err := c.readWS(b, int(h.Length))
if err != nil {
return n, err
}
if !h.Fin && n < len(b) {
n2, err := c.Read(b[n:])
return n + n2, err
}
return n, nil
}
func (c *WSTCP) readWS(b []byte, dataLen int) (int, error) {
max := dataLen
if max > len(b) {
max = len(b)
}
n, err := io.ReadFull(c.wsReader, b[:max])
if err == io.EOF {
err = nil
}
c.remaining = dataLen - n
return n, err
}
func (c *WSTCP) read(b []byte) (int, error) {
if c.firstBytes == nil {
return c.conn.Read(b)
}
n := copy(b, c.firstBytes)
if n < len(c.firstBytes) {
c.firstBytes = c.firstBytes[n:]
return n, nil
}
c.firstBytes = nil
n2, err := c.conn.Read(b[n:])
return n + n2, err
}
func (c *WSTCP) Write(b []byte) (int, error) {
if c.wsWriter == nil {
return c.conn.Write(b)
}
n, err := c.wsWriter.Write(b)
if err != nil {
return n, err
}
return n, c.wsWriter.Flush()
}
func (c *WSTCP) Close() error {
return c.conn.Close()
}