-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathws_conn.go
116 lines (100 loc) · 2.2 KB
/
ws_conn.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package main
import (
"io"
"strings"
"github.com/gorilla/websocket"
"github.com/polevpn/elog"
core "github.com/polevpn/polevpn_core"
)
const (
CH_WEBSOCKET_WRITE_SIZE = 2000
TRAFFIC_LIMIT_INTERVAL = 10
)
type WebSocketConn struct {
conn *websocket.Conn
wch chan []byte
closed bool
handler ProcessHandler
}
func NewWebSocketConn(conn *websocket.Conn, handler ProcessHandler) *WebSocketConn {
return &WebSocketConn{
conn: conn,
closed: false,
wch: make(chan []byte, CH_WEBSOCKET_WRITE_SIZE),
handler: handler,
}
}
func (wsc *WebSocketConn) Close(flag bool) error {
if !wsc.closed {
wsc.closed = true
if wsc.wch != nil {
wsc.wch <- nil
close(wsc.wch)
}
err := wsc.conn.Close()
if flag {
go wsc.handler.OnClosed(wsc, false)
}
return err
}
return nil
}
func (wsc *WebSocketConn) String() string {
return wsc.conn.RemoteAddr().String() + "->" + wsc.conn.LocalAddr().String()
}
func (wsc *WebSocketConn) IsClosed() bool {
return wsc.closed
}
func (wsc *WebSocketConn) Read() {
defer func() {
wsc.Close(true)
}()
defer core.PanicHandler()
for {
mtype, pkt, err := wsc.conn.ReadMessage()
if err != nil {
if err == io.ErrUnexpectedEOF || err == io.EOF || strings.Contains(err.Error(), "close") {
elog.Info(wsc.String(), ",conn closed")
} else {
elog.Error(wsc.String(), ",conn read exception:", err)
}
return
}
if mtype == websocket.BinaryMessage {
wsc.handler.OnRequest(pkt, wsc)
} else {
elog.Info("ws mtype=", mtype)
}
}
}
func (wsc *WebSocketConn) Write() {
defer core.PanicHandler()
for {
pkt, ok := <-wsc.wch
if !ok {
elog.Error(wsc.String(), "get pkt from write channel fail,maybe channel closed")
return
}
if pkt == nil {
elog.Info(wsc.String(), ",exit write process")
return
}
err := wsc.conn.WriteMessage(websocket.BinaryMessage, pkt)
if err != nil {
if err == io.EOF || err == io.ErrUnexpectedEOF || strings.Contains(err.Error(), "close") {
elog.Info(wsc.String(), ",conn closed")
} else {
elog.Error(wsc.String(), ",conn write exception:", err)
}
return
}
}
}
func (wsc *WebSocketConn) Send(pkt []byte) {
if wsc.closed {
return
}
if wsc.wch != nil {
wsc.wch <- pkt
}
}