-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathconn_ws.go
69 lines (61 loc) · 1.32 KB
/
conn_ws.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
package cnet
import (
"bytes"
"net"
"time"
"github.com/gorilla/websocket"
)
type wsConn struct {
*websocket.Conn
buff *bytes.Buffer
}
// NewWebSocketConn converts a websocket.Conn into a net.Conn
func NewWebSocketConn(websocketConn *websocket.Conn) net.Conn {
c := wsConn{
Conn: websocketConn,
buff: &bytes.Buffer{},
}
return &c
}
// Read is not threadsafe though thats okay since there
// should never be more than one reader
func (c *wsConn) Read(dst []byte) (int, error) {
ldst := len(dst)
//use buffer or read new message
var src []byte
if c.buff.Len() > 0 {
src = c.buff.Bytes()
c.buff.Reset()
} else if _, msg, err := c.Conn.ReadMessage(); err == nil {
src = msg
} else {
return 0, err
}
//copy src->dest
var n int
if len(src) > ldst {
//copy as much as possible of src into dst
n = copy(dst, src[:ldst])
//copy remainder into buffer
r := src[ldst:]
c.buff.Write(r)
} else {
//copy all of src into dst
n = copy(dst, src)
}
//return bytes copied
return n, nil
}
func (c *wsConn) Write(b []byte) (int, error) {
if err := c.Conn.WriteMessage(websocket.BinaryMessage, b); err != nil {
return 0, err
}
n := len(b)
return n, nil
}
func (c *wsConn) SetDeadline(t time.Time) error {
if err := c.Conn.SetReadDeadline(t); err != nil {
return err
}
return c.Conn.SetWriteDeadline(t)
}