-
-
Save s0undt3ch/0008e5d5056669e84962a3addb2b4975 to your computer and use it in GitHub Desktop.
Verbose node.js websocket logging server
This file contains hidden or 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
/** | |
* npm install express | |
* npm install console-stamp | |
* | |
* To run: | |
* node echo.js | |
*/ | |
const express = require('express'); | |
const http = require('http'); | |
const url = require('url'); | |
const WebSocket = require('ws'); | |
require('console-stamp')(console, 'HH:MM:ss.l'); | |
const app = express(); | |
app.use(function (req, res) { | |
res.send({'ret': {}}); | |
}); | |
const server = http.createServer(app); | |
const wss = new WebSocket.Server({ server }); | |
function heartbeat() { | |
this.isAlive = true; | |
} | |
wss.on('connection', function connection(ws, req) { | |
const location = url.parse(req.url, true); | |
// You might use location.query.access_token to authenticate or share sessions | |
// or req.headers.cookie (see http://stackoverflow.com/a/16395220/151312) | |
ws.on('open', function open() { | |
console.log('connected'); | |
}); | |
ws.on('close', function close() { | |
console.log('disconnected'); | |
}); | |
ws.on('message', function incoming(message) { | |
console.log('received: %s', message); | |
ret = JSON.parse(message); | |
// Add the expected payload fields | |
ret['result'] = {}; | |
ret['error'] = null; | |
ret['warnings'] = []; | |
ret = JSON.stringify(ret) | |
/// Send it back | |
console.log('sending: %s', ret); | |
ws.send(ret); | |
}); | |
ws.isAlive = true; | |
ws.on('pong', heartbeat); | |
const interval = setInterval(function ping() { | |
wss.clients.forEach(function each(ws) { | |
if (ws.isAlive === false) { | |
console.log('Stale connection terminating.'); | |
return ws.terminate(); | |
} | |
ws.isAlive = false; | |
ws.ping('', false, true); | |
}); | |
}, 10000); | |
console.log('First connected'); | |
ws.send('{}'); | |
}); | |
server.listen(8080, function listening() { | |
console.log('Listening on %d', server.address().port); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment