2015-03-19 12:10:41 -07:00
|
|
|
/**
|
2015-03-23 11:48:02 -07: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 12:10:41 -07:00
|
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
|
|
|
|
|
|
|
|
function attachToServer(server, path) {
|
2015-10-12 16:46:52 -07:00
|
|
|
var WebSocketServer = require('ws').Server;
|
2015-03-19 12:10:41 -07:00
|
|
|
var wss = new WebSocketServer({
|
|
|
|
server: server,
|
|
|
|
path: path
|
|
|
|
});
|
|
|
|
var clients = [];
|
|
|
|
|
2015-07-23 16:56:23 -07:00
|
|
|
function sendSpecial(message) {
|
|
|
|
clients.forEach(function (cn) {
|
|
|
|
try {
|
|
|
|
cn.send(JSON.stringify(message));
|
|
|
|
} catch(e) {
|
2015-10-23 11:28:49 -07:00
|
|
|
// Sometimes this call throws 'not opened'
|
2015-07-23 16:56:23 -07:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2015-03-19 12:10:41 -07:00
|
|
|
wss.on('connection', function(ws) {
|
2015-07-23 16:56:23 -07:00
|
|
|
var id = Math.random().toString(15).slice(10, 20);
|
|
|
|
sendSpecial({$open: id});
|
2015-03-19 12:10:41 -07: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 16:56:23 -07:00
|
|
|
sendSpecial({$error: id});
|
2015-03-19 12:10:41 -07:00
|
|
|
};
|
|
|
|
|
|
|
|
ws.onclose = function() {
|
|
|
|
clients = allClientsExcept(ws);
|
2015-07-23 16:56:23 -07:00
|
|
|
sendSpecial({$close: id});
|
2015-03-19 12:10:41 -07:00
|
|
|
};
|
|
|
|
|
|
|
|
ws.on('message', function(message) {
|
|
|
|
allClientsExcept(ws).forEach(function(cn) {
|
2015-04-24 14:57:24 -07:00
|
|
|
try {
|
|
|
|
cn.send(message);
|
|
|
|
} catch(e) {
|
2015-10-07 10:47:58 -07:00
|
|
|
// Sometimes this call throws 'not opened'
|
2015-04-24 14:57:24 -07:00
|
|
|
}
|
2015-03-19 12:10:41 -07:00
|
|
|
});
|
|
|
|
});
|
|
|
|
});
|
2015-10-05 09:15:10 -07:00
|
|
|
|
2015-10-23 11:28:49 -07:00
|
|
|
return {
|
|
|
|
server: wss,
|
2015-10-23 13:56:10 -07:00
|
|
|
isChromeConnected: function() {
|
|
|
|
return clients
|
|
|
|
.map(function(ws) { return ws.upgradeReq.headers['user-agent']; })
|
2015-10-23 11:28:49 -07:00
|
|
|
.filter(Boolean)
|
2015-10-26 12:59:54 -07:00
|
|
|
.some(function(userAgent) { return userAgent.includes('Chrome'); });
|
2015-10-23 13:56:10 -07:00
|
|
|
}
|
2015-10-23 11:28:49 -07:00
|
|
|
};
|
2015-03-19 12:10:41 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
attachToServer: attachToServer
|
|
|
|
};
|