forked from jpillora/chisel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn_ws.go
68 lines (61 loc) · 1.3 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
package cnet
import (
"net"
"time"
"github.com/gorilla/websocket"
)
type wsConn struct {
*websocket.Conn
buff []byte
}
//NewWebSocketConn converts a websocket.Conn into a net.Conn
func NewWebSocketConn(websocketConn *websocket.Conn) net.Conn {
c := wsConn{
Conn: websocketConn,
}
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 len(c.buff) > 0 {
src = c.buff
c.buff = nil
} 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:]
lr := len(r)
c.buff = make([]byte, lr)
copy(c.buff, 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)
}