You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

52 lines
1.4 KiB

const WebSocket = require('ws');
const UrlParser = require('url');
const uuid = require('node-uuid');
const Messenger = require('./messenger');
const RicochetApp = require(`${__dirname}/../server/ricochet.js`);
const apps = {
'/ricochet': new RicochetApp({ messenger: new Messenger() })
};
// Make sure all apps follow the messaging contract.
Object.keys(apps).forEach((key) => {
const app = apps[key];
const valid = app && app.messenger && app.onConnect && app.onMessage && app.onDisconnect;
if (!valid) {
delete apps[key];
console.log(`Application at ${key} is missing one or more: messenger, onConnect, onMessage, onDisconnect.`);
}
});
const onConnect = (ws, req) => {
// Store an ID on the socket connection.
ws.id = uuid.v4();
const url = UrlParser.parse(req.url, true);
const app = apps[url.pathname];
if (app) {
app.messenger.subscribe(ws);
app.onConnect(ws, req);
ws.on('message', (rawBody) => {
app.onMessage(ws, rawBody);
});
ws.on('close', () => {
app.onDisconnect(ws);
app.messenger.unsubscribe(ws);
});
}
};
//===== Generic socket server for any application instantiated above.
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', onConnect);
console.log("Websocket server listening on :8080");