Skip to content

Instantly share code, notes, and snippets.

@edygar
Last active November 17, 2015 21:01
Show Gist options
  • Save edygar/ba87856d011ff94ac17f to your computer and use it in GitHub Desktop.
Save edygar/ba87856d011ff94ac17f to your computer and use it in GitHub Desktop.
Receives request of pings to desired hostnames and responds with the pongs at its arrival through WebSocket
import netPing from 'net-ping';
import express from 'express';
import http from 'http';
import dns from 'dns';
import socketIO from 'socket.io';
import { BehaviorSubject, Observable } from 'rx';
const app = express();
const server = http.Server(app);
const io = socketIO(server);
const pingSession = netPing.createSession();
const resolve = Observable.fromNodeCallback(dns.resolve);
const ping = Observable.fromNodeCallback(
pingSession.pingHost,
pingSession,
(host, requestTime, responseTime)=> ({
host, requestTime, responseTime,
})
);
app.get('/', (req, res) =>
res.sendFile(__dirname + '/index.html')
);
function pingHostname(hostname) {
const startTime = new Date();
return resolve(hostname)
.flatMap((addresses) =>
ping(addresses[0])
.map((pong) => ({ ...pong, startTime, hostname }))
)
.catch((error) =>
Observable.return({
hostname,
error,
startTime,
})
)
.map(pong => ({...pong, endTime: new Date() }));
}
io
.on('connection', (socket) => {
const hosts$ = new BehaviorSubject([]);
// For each 10s from the connection
const monitoring = Observable.interval(10000)
// Gets current hosts list
.withLatestFrom(hosts$, (interval, hosts) => hosts)
// Sends a Ping for each hosts
.flatMap(hosts => Observable.merge(hosts.map(pingHostname)))
// ignores hosts no longer in the list on their arrival
.withLatestFrom( hosts$,
(pong, hosts) => hosts.indexOf(pong.hostname) !== -1 ? pong : null
)
.filter(pong => pong)
// Emits to interested client
.subscribe(pong => socket.emit('pong', pong));
// Sets the hosts user is interested
Observable.fromEvent(socket, 'setHosts')
.map(hosts => JSON.parse(hosts))
.subscribe(hosts$);
// Ends monitoring on disconnect
Observable.fromEvent(socket, 'disconnect')
.subscribe(() => monitoring.dispose() );
});
server.listen(3000, () => {
console.log('Listening on *:3000');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment