forked from lzjluzijie/websocks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mux.go
132 lines (112 loc) · 2.33 KB
/
mux.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package core
import (
"io"
"math/rand"
"net"
"sync"
"sync/atomic"
)
const (
MessageMethodData = iota
MessageMethodDial
)
type Message struct {
Method byte
ConnID uint64
MessageID uint64
Data []byte
}
type MuxConn struct {
ID uint64
MuxWS *MuxWebSocket
mutex sync.Mutex
buf []byte
wait chan int
receiveMessageID uint64
sendMessageID *uint64
}
//NewMuxConn create new mux connection for client
func NewMuxConn(muxWS *MuxWebSocket) (conn *MuxConn) {
return &MuxConn{
ID: rand.Uint64(),
MuxWS: muxWS,
wait: make(chan int),
sendMessageID: new(uint64),
}
}
func (conn *MuxConn) Write(p []byte) (n int, err error) {
m := &Message{
Method: MessageMethodData,
ConnID: conn.ID,
MessageID: conn.SendMessageID(),
Data: p,
}
err = conn.MuxWS.SendMessage(m)
if err != nil {
return 0, err
}
return len(p), nil
}
func (conn *MuxConn) Read(p []byte) (n int, err error) {
if len(conn.buf) == 0 {
logger.Debugf("%d buf is 0, waiting", conn.ID)
<-conn.wait
}
conn.mutex.Lock()
logger.Debugf("%d buf: %v", conn.buf)
n = copy(p, conn.buf)
conn.buf = conn.buf[n:]
conn.mutex.Unlock()
return
}
func (conn *MuxConn) HandleMessage(m *Message) (err error) {
logger.Debugf("handle message %d %d", m.ConnID, m.MessageID)
for {
if conn.receiveMessageID == m.MessageID {
conn.mutex.Lock()
conn.buf = append(conn.buf, m.Data...)
conn.receiveMessageID++
close(conn.wait)
conn.wait = make(chan int)
conn.mutex.Unlock()
logger.Debugf("handled message %d %d", m.ConnID, m.MessageID)
return
}
<-conn.wait
}
return
}
func (conn *MuxConn) SendMessageID() (id uint64) {
id = atomic.LoadUint64(conn.sendMessageID)
atomic.AddUint64(conn.sendMessageID, 1)
return
}
func (conn *MuxConn) Run(c *net.TCPConn) {
go func() {
_, err := io.Copy(c, conn)
if err != nil {
logger.Debugf(err.Error())
}
}()
_, err := io.Copy(conn, c)
if err != nil {
logger.Debugf(err.Error())
}
return
}
//client dial remote
func (conn *MuxConn) DialMessage(host string) (err error) {
m := &Message{
Method: MessageMethodDial,
MessageID: 18446744073709551615,
ConnID: conn.ID,
Data: []byte(host),
}
logger.Debugf("dial for %s", host)
err = conn.MuxWS.SendMessage(m)
if err != nil {
return
}
logger.Debugf("%d %s", conn.ID, host)
return
}