-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathwebsockets.js
More file actions
76 lines (62 loc) · 2.26 KB
/
Copy pathwebsockets.js
File metadata and controls
76 lines (62 loc) · 2.26 KB
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
var net = require('net')
var wsock = require('websock')
var settings = require('./settings')
var openCount = 0
wsock.listen(settings.websockets.listen_port, ws_connect);
console.log("websockets listening on " + settings.websockets.listen_port)
function ws_connect(socket) {
var apis = []
openCount += 1
console.log('websockets #' + openCount + ' open.')
apiAdd(apis, socket, 'api.icecondor.com', settings.api.listen_port)
//apiAdd(apis, socket, 'staging.icecondor.com', settings.api.listen_port, true)
socket.on('message', function(data) {
for (const api of apis) {
console.log(api._host + ':' + settings.api.listen_port + ' <- ' + socket.connection._peername.address + ':' + socket.connection._peername.port, data.toString().trim())
api.write(data + "\n")
}
})
socket.on('close', function() {
openCount -= 1
console.log('websocket closed. ' + openCount + ' remaining.');
for (const api of apis) api.end()
})
}
function apiAdd(apis, socket, host, port, silent) {
console.log('connecting to api on ', port, silent ? "SILENT MODE" : "");
var sockApi = silent ? silentRelayTo(socket, host, port) : relayTo(socket, host, port)
if (sockApi) {
apis.push(sockApi)
} else {
console.log('api socket open fail for', host + ':' + port)
}
}
function relayTo(socket, host, port) {
var apiSocket = new net.Socket();
apiSocket.on('data', function(data) {
console.log(host + ':' + port + ' -> ' + socket.connection._peername.address + ':' + socket.connection._peername.port, data.toString().trim())
socket.send(data)
})
apiSocket.on('error', function(exception) {
console.log("apiSocket error: " + exception);
apiSocket.end()
socket.end()
})
apiSocket.on('close', function() {
console.log('api ' + host + ' closed. closing client');
socket.end()
})
apiSocket.connect(port, host)
return apiSocket
}
function silentRelayTo(socket, host, port) {
var apiSocket = new net.Socket();
apiSocket.on('data', function(data) {
console.log(host + ':' + port + ' [muted]-> :' + socket.connection._peername.port + ' ' + data.toString().trim())
})
apiSocket.on('error', function(exception) {
console.log(host, 'silent socket fail ignored')
})
apiSocket.connect(port, host)
return apiSocket
}