Skip to content

Commit

Permalink
Update package websocket to ws and improve errors
Browse files Browse the repository at this point in the history
  • Loading branch information
brunnolou committed Dec 27, 2017
1 parent be256a1 commit 3431c44
Show file tree
Hide file tree
Showing 6 changed files with 68 additions and 75 deletions.
11 changes: 8 additions & 3 deletions app/components/Broadcast.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
const store = require('../store');
const events = require('../events');

function Broadcast(event, data) {
function Broadcast(event, data, collection) {
const connections = Object.values(store.activeConnections);

if (!Object.values(events).includes(event)) return console.log('Invalid event:', event);

connections.forEach(({ connection, id }) => {
if (!connection) return;

connection.send(JSON.stringify({ event, data }));
connection.send(JSON.stringify({ event, data, collection }), (error) => {
if (!error) return;

console.log('Broadcasted event: ', id, event);
// If connection no longer exists delete it.
delete connections[id];
});

console.log('Broadcasted event: ', [id], event);
});

return Object.keys(store.activeConnections);
Expand Down
32 changes: 22 additions & 10 deletions app/components/Connect.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,39 @@ const store = require('../store');
const events = require('../events');
const Broadcast = require('./Broadcast');

function Connect(connection, { protocol }) {
function Connect(connection, req) {
const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;

// 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)

const id = store.globalCounter;

store.activeConnections[id] = { connection, id };

// Connected.
connection.sendUTF(JSON.stringify({ event: events.CONNECT }));
connection.send(JSON.stringify({ event: events.CONNECT }));
store.globalCounter += 1;

connection.on('message', (message) => {
if (message.type !== 'utf8') return;

// Only broadcast preview messages.
if (protocol !== 'preview-protocol') return;

Broadcast(events.COLLECTIONS_PREVIEW);
let data;
try {
data = JSON.parse(message);
} catch (error) {
return;
}

Broadcast(data.event, data.entry);
});

connection.on('close', (reasonCode, description) => {
console.log(`${new Date()} Peer ${connection.remoteAddress} disconnected. ${description}`);
connection.on('error', (error) => {
console.log(`${new Date()} Peer ${ip} disconnected. ${error}`);
delete store.activeConnections[connection.id];
});

connection.on('close', (error) => {
console.log(`${new Date()} Peer ${ip} disconnected. ${error}`);
delete store.activeConnections[connection.id];
});
}
Expand Down
4 changes: 2 additions & 2 deletions app/webServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ function webServer() {
app.use(bodyParser.json());

app.post('/update', (req, res) => {
const { body: { event, args } } = req.body;
const { body: { event, args } } = req;

Broadcast(event, args);
Broadcast(event, args[1], args[0]);

res.send('ok');
});
Expand Down
34 changes: 5 additions & 29 deletions app/webSocketServer.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,11 @@
const WebSocketServer = require('websocket').server;
const WebSocketRouter = require('websocket').router;
const WebSocket = require('ws');
const Connect = require('./components/Connect');

const originIsAllowed = origin => true || origin;
function webSocketServer(server) {
const wss = new WebSocket.Server({ server });

function webSocketServer(httpServer) {
const wsServer = new WebSocketServer({
httpServer,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false,
});

// Ws Router.
const router = new WebSocketRouter();

router.attachServer(wsServer);

// Accepts all protocols.
router.mount('*', '*', (request) => {
if (!originIsAllowed(request.origin)) {
request.reject();
return;
}

const connection = request.accept(request.origin);

Connect(connection, request);
wss.on('connection', (connection, req) => {
Connect(connection, req);
});
}

Expand Down
60 changes: 30 additions & 30 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"fetch": "^1.1.0",
"isomorphic-fetch": "^2.2.1",
"node-fetch": "^2.0.0-alpha.9",
"websocket": "^1.0.24"
"ws": "^3.3.3"
},
"devDependencies": {
"eslint": "^4.11.0",
Expand Down

0 comments on commit 3431c44

Please sign in to comment.