mirror of
https://we.phorge.it/source/phorge.git
synced 2024-12-03 04:02:43 +01:00
4af1fd2a79
Summary: Ref T7110. Listeners are now removed when clients close the connection to avoid stacking a never ending number of unused listeners. Test Plan: Using `wscat` to connect to the Aphlict server; when closing the connection a 'Diconnected.' will appear in the logs and the number of active listeners is decreased by one. Reviewers: epriestley, #blessed_reviewers Reviewed By: epriestley, #blessed_reviewers Subscribers: Korvin, epriestley Maniphest Tasks: T7110 Differential Revision: https://secure.phabricator.com/D11634
97 lines
2.3 KiB
JavaScript
97 lines
2.3 KiB
JavaScript
'use strict';
|
|
|
|
var JX = require('./javelin').JX;
|
|
|
|
require('./AphlictListenerList');
|
|
require('./AphlictLog');
|
|
|
|
var util = require('util');
|
|
var WebSocket = require('ws');
|
|
|
|
JX.install('AphlictClientServer', {
|
|
|
|
construct: function(server) {
|
|
this.setListenerList(new JX.AphlictListenerList());
|
|
this.setLogger(new JX.AphlictLog());
|
|
this._server = server;
|
|
},
|
|
|
|
members: {
|
|
_server: null,
|
|
|
|
listen: function() {
|
|
var self = this;
|
|
var server = this._server.listen.apply(this._server, arguments);
|
|
var wss = new WebSocket.Server({server: server});
|
|
|
|
wss.on('connection', function(ws) {
|
|
var listener = self.getListenerList().addListener(ws);
|
|
|
|
function log() {
|
|
self.getLogger().log(
|
|
util.format('<%s>', listener.getDescription()) +
|
|
' ' +
|
|
util.format.apply(null, arguments));
|
|
}
|
|
|
|
log('Connected from %s.', ws._socket.remoteAddress);
|
|
|
|
ws.on('message', function(data) {
|
|
log('Received message: %s', data);
|
|
|
|
var message;
|
|
try {
|
|
message = JSON.parse(data);
|
|
} catch (err) {
|
|
log('Message is invalid: %s', err.message);
|
|
return;
|
|
}
|
|
|
|
switch (message.command) {
|
|
case 'subscribe':
|
|
log(
|
|
'Subscribed to: %s',
|
|
JSON.stringify(message.data));
|
|
listener.subscribe(message.data);
|
|
break;
|
|
|
|
case 'unsubscribe':
|
|
log(
|
|
'Unsubscribed from: %s',
|
|
JSON.stringify(message.data));
|
|
listener.unsubscribe(message.data);
|
|
break;
|
|
|
|
default:
|
|
log(
|
|
'Unrecognized command "%s".',
|
|
message.command || '<undefined>');
|
|
}
|
|
});
|
|
|
|
ws.on('close', function() {
|
|
self.getListenerList().removeListener(listener);
|
|
log('Disconnected.');
|
|
});
|
|
|
|
wss.on('close', function() {
|
|
self.getListenerList().removeListener(listener);
|
|
log('Disconnected.');
|
|
});
|
|
|
|
wss.on('error', function(err) {
|
|
log('Error: %s', err.message);
|
|
});
|
|
|
|
});
|
|
|
|
},
|
|
|
|
},
|
|
|
|
properties: {
|
|
listenerList: null,
|
|
logger: null,
|
|
}
|
|
|
|
});
|