-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcp-websocket-tunnel.js
54 lines (35 loc) · 1.13 KB
/
tcp-websocket-tunnel.js
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
const net = require('net')
const WebSocket = require('ws')
exports.toWebSocket = (fromPort, toAddr) => {
const server = net.createServer(c => {
const ws = new WebSocket(toAddr)
ws.on('close', () => c.destroy())
ws.on('error', () => c.destroy())
c.on('end', () => ws.close(1000))
c.on('error', () => ws.close(1000))
ws.on('open', () => c.on('data', data => ws.send(data)))
ws.on('message', data => {
if (!c.destroyed)
c.write(data)
})
})
server.on('error', (err) => {
throw err
})
server.listen(fromPort)
return server
}
exports.toTCP = (fromPort, toPort, toHost) => {
const wss = new WebSocket.WebSocketServer({ port: fromPort })
wss.on('connection', ws => this.toTCPOnConnection(ws, toPort, toHost))
return wss
}
exports.toTCPOnConnection = (ws, toPort, toHost) => {
const client = net.connect(toPort, toHost)
client.on('end', () => ws.close(1000))
client.on('error', () => ws.close(1000))
ws.on('close', () => client.destroy())
ws.on('error', () => client.destroy())
ws.on('message', data => client.write(data))
client.on('data', data => ws.send(data))
}