2 var WebSocketServer = require('ws').Server;
3 const serviceWsClientIp = "1";
8 var RelayServer = function(httpserver, options) {
9 var wsServer = new WebSocketServer({ server : httpserver });
11 wsServer.on('connection', function(ws, req) {
12 // In case of local client, remoteAddress will be ::1
13 // In case of remote client, remoteAddress will be ::ffff:ipaddress
14 // e.g.) ::ffff:192.168.0.21
15 const rawIp = req.socket.remoteAddress;
16 const ip = rawIp.slice(rawIp.lastIndexOf(":") + 1);
17 const pkgId = req.url.slice(1); // get the substring after '/' from req.url
19 if (serviceWs[pkgId] === undefined) {
20 serviceWs[pkgId] = null;
22 if (wsClients[pkgId] === undefined) {
23 wsClients[pkgId] = [];
25 if (ip === serviceWsClientIp || ip === '127.0.0.1') {
26 console.log("connected from local");
27 serviceWs[pkgId] = ws;
28 if (!wsClients[pkgId].length)
29 console.log("connected : no client-clients");
30 ws.on('message', function(msg) {
31 console.log("msg[" + msg + "]");
32 const res_msg = 'Success to send : ' + msg;
35 for (let key in serviceWs) {
36 if (serviceWs[key] === ws) {
42 let id = JSON.parse(msg).id;
44 // Do what need to handle in relay server only
47 if (!wsClients[myPkgId].length)
50 for (let client of wsClients[myPkgId])
53 if (id < wsClients[myPkgId].length)
54 wsClients[myPkgId][id].send(msg);
57 ws.on('close', function(msg) {
58 console.log("close server-client");
61 console.log("connected from", ip);
62 if (wsClients[pkgId].indexOf(ws) == -1) {
63 wsClients[pkgId].push(ws);
64 let index = wsClients[pkgId].length - 1;
65 let res = JSON.stringify({type: "id", data: index, id: -1});
67 if (serviceWs[pkgId] === null)
68 console.log("connected : no server-client")
70 serviceWs[pkgId].send(JSON.stringify({type: "new_client", data: index, id: -1}));
73 ws.on('message', function(msg) {
74 console.log("msg[" + msg + "]");
75 const res_msg = 'Success to send : ' + msg;
78 for (let key in wsClients) {
79 if (wsClients[key].indexOf(ws) != -1) {
85 if (serviceWs[myPkgId])
86 serviceWs[myPkgId].send(msg);
88 ws.on('close', function(msg) {
89 console.log("close client-clients");
91 for (let key in wsClients) {
92 if (wsClients[key].indexOf(ws) != -1) {
98 let index = wsClients[myPkgId].indexOf(ws);
99 wsClients[myPkgId].splice(index, 1);
100 serviceWs[myPkgId].send(JSON.stringify({type: "client_disconnect", data: {totalcount: wsClients[myPkgId].length, id: index}, id: -1}));
106 module.exports = RelayServer;