forked from kataras/neffos
/
socket.go
84 lines (66 loc) · 1.95 KB
/
socket.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
package gorilla
import (
"net"
"net/http"
"sync"
"time"
neffos "github.com/WolffunService/wolfsocket"
gorilla "github.com/gorilla/websocket"
)
// Socket completes the `neffos.Socket` interface,
// it describes the underline websocket connection.
type Socket struct {
UnderlyingConn *gorilla.Conn
request *http.Request
client bool
mu sync.Mutex
}
func newSocket(underline *gorilla.Conn, request *http.Request, client bool) *Socket {
return &Socket{
UnderlyingConn: underline,
request: request,
client: client,
}
}
// NetConn returns the underline net connection.
func (s *Socket) NetConn() net.Conn {
return s.UnderlyingConn.UnderlyingConn()
}
// Request returns the http request value.
func (s *Socket) Request() *http.Request {
return s.request
}
// ReadData reads binary or text messages from the remote connection.
func (s *Socket) ReadData(timeout time.Duration) ([]byte, neffos.MessageType, error) {
for {
if timeout > 0 {
s.UnderlyingConn.SetReadDeadline(time.Now().Add(timeout))
}
opCode, data, err := s.UnderlyingConn.ReadMessage()
if err != nil {
return nil, 0, err
}
if opCode != gorilla.BinaryMessage && opCode != gorilla.TextMessage {
// if gorilla.IsUnexpectedCloseError(err, gorilla.CloseGoingAway) ...
continue
}
return data, neffos.MessageType(opCode), err
}
}
// WriteBinary sends a binary message to the remote connection.
func (s *Socket) WriteBinary(body []byte, timeout time.Duration) error {
return s.write(body, gorilla.BinaryMessage, timeout)
}
// WriteText sends a text message to the remote connection.
func (s *Socket) WriteText(body []byte, timeout time.Duration) error {
return s.write(body, gorilla.TextMessage, timeout)
}
func (s *Socket) write(body []byte, opCode int, timeout time.Duration) error {
if timeout > 0 {
s.UnderlyingConn.SetWriteDeadline(time.Now().Add(timeout))
}
s.mu.Lock()
err := s.UnderlyingConn.WriteMessage(opCode, body)
s.mu.Unlock()
return err
}