2015-03-19 19:10:41 +00:00
|
|
|
/**
|
2015-03-23 18:48:02 +00:00
|
|
|
* Copyright (c) 2015-present, Facebook, Inc.
|
|
|
|
* All rights reserved.
|
|
|
|
*
|
|
|
|
* This source code is licensed under the BSD-style license found in the
|
|
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
2015-03-19 19:10:41 +00:00
|
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
|
|
|
|
var WebSocketServer = require('ws').Server;
|
|
|
|
|
|
|
|
function attachToServer(server, path) {
|
|
|
|
var wss = new WebSocketServer({
|
|
|
|
server: server,
|
|
|
|
path: path
|
|
|
|
});
|
|
|
|
var clients = [];
|
|
|
|
|
2015-07-23 23:56:23 +00:00
|
|
|
function sendSpecial(message) {
|
|
|
|
clients.forEach(function (cn) {
|
|
|
|
try {
|
|
|
|
cn.send(JSON.stringify(message));
|
|
|
|
} catch(e) {
|
|
|
|
console.warn('WARN: ' + e.message);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2015-03-19 19:10:41 +00:00
|
|
|
wss.on('connection', function(ws) {
|
2015-07-23 23:56:23 +00:00
|
|
|
var id = Math.random().toString(15).slice(10, 20);
|
|
|
|
sendSpecial({$open: id});
|
2015-03-19 19:10:41 +00:00
|
|
|
clients.push(ws);
|
|
|
|
|
|
|
|
var allClientsExcept = function(ws) {
|
|
|
|
return clients.filter(function(cn) { return cn !== ws; });
|
|
|
|
};
|
|
|
|
|
|
|
|
ws.onerror = function() {
|
|
|
|
clients = allClientsExcept(ws);
|
2015-07-23 23:56:23 +00:00
|
|
|
sendSpecial({$error: id});
|
2015-03-19 19:10:41 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
ws.onclose = function() {
|
|
|
|
clients = allClientsExcept(ws);
|
2015-07-23 23:56:23 +00:00
|
|
|
sendSpecial({$close: id});
|
2015-03-19 19:10:41 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
ws.on('message', function(message) {
|
|
|
|
allClientsExcept(ws).forEach(function(cn) {
|
2015-04-24 21:57:24 +00:00
|
|
|
try {
|
|
|
|
cn.send(message);
|
|
|
|
} catch(e) {
|
2015-10-07 17:47:58 +00:00
|
|
|
// Sometimes this call throws 'not opened'
|
2015-04-24 21:57:24 +00:00
|
|
|
}
|
2015-03-19 19:10:41 +00:00
|
|
|
});
|
|
|
|
});
|
|
|
|
});
|
2015-10-05 16:15:10 +00:00
|
|
|
|
|
|
|
return wss;
|
2015-03-19 19:10:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
attachToServer: attachToServer
|
|
|
|
};
|