-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreadwriterconn.go
58 lines (47 loc) · 1.02 KB
/
readwriterconn.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
package main
import (
"io"
"github.com/smith-30/websocket"
)
// ReadWriterConn wraps the *websocket.Conn to satisfy the io.ReadWriter interface.
type ReadWriterConn struct {
*websocket.Conn
writeMsgTyp int
rd io.Reader
}
// NewReadWriterConn returns a new ReadWriterConn instance.
func NewReadWriterConn(conn *websocket.Conn, writeMessageType int) *ReadWriterConn {
return &ReadWriterConn{
Conn: conn,
writeMsgTyp: writeMessageType,
}
}
// Read implements the io.Reader interface.
func (rwc *ReadWriterConn) Read(p []byte) (int, error) {
again:
if rwc.rd == nil {
_, rd, err := rwc.NextReader()
if err != nil {
return 0, err
}
rwc.rd = rd
}
n, err := rwc.rd.Read(p)
if err == io.EOF {
rwc.rd = nil
goto again
}
return n, err
}
// Write implements the io.Writer interface.
func (rwc *ReadWriterConn) Write(p []byte) (int, error) {
wr, err := rwc.NextWriter(rwc.writeMsgTyp)
if err != nil {
return 0, err
}
n, err := wr.Write(p)
if err != nil {
return n, err
}
return n, wr.Close()
}