-
-
Save sylwesterdigital/08e8ad725ce3633b0b065665104415de to your computer and use it in GitHub Desktop.
Websocket Server in Node JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const https = require('https'); | |
const fs = require('fs'); | |
const express = require('express'); | |
const path = require('path'); | |
const { createServer } = require('http'); | |
const WebSocket = require('ws'); | |
const app = express(); | |
const port = 2222; | |
const server = https.createServer({ | |
// you need to change this, depends on your own SSL environment, | |
// see - https://letsencrypt.org/getting-started/ and https://certbot.eff.org/ | |
// also - https://nginx.org/en/docs/http/configuring_https_servers.html | |
// self signed cert for localhost and development | |
/* | |
openssl req -x509 -out localhost.crt -keyout localhost.key \ | |
-newkey rsa:2048 -nodes -sha256 \ | |
-subj '/CN=localhost' -extensions EXT -config <( \ | |
printf "[dn]\nCN=localhost\n[req]\ndistinguished_name = dn\n[EXT]\nsubjectAltName=DNS:localhost\nkeyUsage=digitalSignature\nextendedKeyUsage=serverAuth") | |
*/ | |
key: fs.readFileSync('../ssl/localhost.key'), | |
cert: fs.readFileSync('../ssl/localhost.crt') | |
}, app); | |
function getmem() { | |
const used = process.memoryUsage(); | |
let memstr = '' | |
for (let key in used) { | |
memstr += `${key} ${Math.round(used[key] / 1024 / 1024 * 100) / 100} MB\n` | |
} | |
return memstr; | |
} | |
function isJsonString(str) { | |
try { | |
JSON.parse(str); | |
} catch (e) { | |
return false; | |
} | |
return true; | |
} | |
function sendAllExcept(message, ids) { | |
if (undefined === ids) throw new Error('ids must be specified'); | |
if (!Array.isArray(ids)) ids = [ids]; | |
for (var i = 0, cLength = CLIENTS.length; i < cLength; i++) { | |
if (ids.indexOf(i) !== -1) continue; | |
CLIENTS[i].send(message); | |
} | |
} | |
var CLIENTS = []; | |
var id; | |
const wss = new WebSocket.Server({ server }); | |
wss.on('connection', function(ws) { | |
id = Math.random(); | |
console.log('connection is established : ' + id); | |
CLIENTS[id] = ws; | |
CLIENTS.push(ws); | |
id = setInterval(function() { | |
ws.send(JSON.stringify({ function: "showStats", args: { str: getmem() } }), function() {}); | |
}, 2000); | |
console.log('started client interval'); | |
ws.on('close', function() { | |
console.log('stopping client interval'); | |
clearInterval(id); | |
}); | |
ws.on('message', function(message) { | |
let messageType = typeof message; | |
if (messageType == "object") { | |
console.log("really object") | |
} | |
if (isJsonString(message)) { | |
console.log("this is JSON"); | |
// if JSON, let's parse it | |
let obj = JSON.parse(message); | |
console.log("function:", obj.function) | |
console.log("args:", obj.args) | |
if (obj.function == "lightUp") | |
for (let e = 0; e < CLIENTS.length; e++) { | |
CLIENTS[e].send(JSON.stringify({ function: "lightUp", args: obj.args }), function() {}); | |
} | |
} else { | |
console.log("not a JSON:", String("String: " + message)); | |
} | |
}); | |
}); | |
server.listen(port, function() { | |
console.log('Listening on:' + port); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment