-
Notifications
You must be signed in to change notification settings - Fork 38
/
ws.js
59 lines (50 loc) · 1.8 KB
/
ws.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
55
56
57
58
59
import { WebSocketServer } from "ws";
import net from "net";
function createSocket(host, port, callback) {
const socket = net.connect({
host: host,
port: port
}, function (err) {
if (err) return callback(err);
});
socket.on('error', function (err) {
callback(err);
});
return socket;
}
export function WS(server, settings) {
const wss = new WebSocketServer({
server: server
});
wss.on('connection', function connection(ws, req) {
ws.once('message', function incoming(targetInfo) {
// First message is the information about the target server
let { server, port } = JSON.parse(targetInfo);
if (settings.val.forcedefault) {
server = settings.val.default.host;
port = settings.val.default.port;
}
const socket = createSocket(server, port, (err) => {
if (err) return ws.send(err.toString());
});
ws.on('message', function (data) {
socket.write(data, 'binary', function () {
// console.log('Sent: ', (flags.buffer || chunk).toString());
});
});
socket.on('data', function (chunk) {
// console.log('Received: ', chunk.toString());
// Providing a callback is important, otherwise errors can be thrown
ws.send(chunk, { binary: true }, (err) => err && console.error(err));
});
socket.on('end', function () {
console.log('TCP connection closed by remote');
ws.close();
});
ws.on('close', function () {
console.log('Websocket connection closed');
socket.end();
});
});
});
}