-
Notifications
You must be signed in to change notification settings - Fork 0
/
writer.go
79 lines (61 loc) · 1.17 KB
/
writer.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
package websocket
const defaultWriteBufferSize = 4096
type messageWriter struct {
conn *Conn
messageType byte
wasFragment bool
pos int
buff []byte
}
func newMessageWriter(conn *Conn, frameType byte) *messageWriter {
return &messageWriter{
conn: conn,
messageType: frameType,
buff: make([]byte, defaultWriteBufferSize),
}
}
func (w *messageWriter) Write(p []byte) (int, error) {
if w.conn.closeErr != nil {
return 0, w.conn.closeErr
}
n := 0
for len(p) > 0 {
if len(w.buff[w.pos:]) == 0 {
fr := frame{
isFragment: true,
opcode: w.getOpcode(),
payload: w.buff,
}
err := w.conn.send(fr)
if err != nil {
return 0, err
}
w.pos = 0
w.wasFragment = true
}
nn := copy(w.buff[w.pos:], p)
p = p[nn:]
n += nn
w.pos += nn
}
return n, nil
}
func (w *messageWriter) getOpcode() byte {
if w.wasFragment {
return ContinuationOpcode
}
return w.messageType
}
func (w *messageWriter) Close() error {
if w.conn.closeErr != nil {
return w.conn.closeErr
}
fr := frame{
opcode: w.getOpcode(),
payload: w.buff[:w.pos],
}
if err := w.conn.send(fr); err != nil {
return err
}
return nil
}