diff --git a/packages/xo-server/src/index.mjs b/packages/xo-server/src/index.mjs index 1f957d2ee..e7f848a71 100644 --- a/packages/xo-server/src/index.mjs +++ b/packages/xo-server/src/index.mjs @@ -554,18 +554,11 @@ const setUpApi = (webServer, xo, config) => { }) xo.hooks.on('stop', () => fromCallback.call(webSocketServer, 'close')) - let n = 0 - const onConnection = (socket, upgradeReq) => { const { remoteAddress } = upgradeReq.socket - ++n - - log.info(`+ WebSocket connection (${remoteAddress}) (${n} connected)`) - // Create the abstract XO object for this connection. - const connection = xo.createUserConnection() - connection.set('user_ip', remoteAddress) + const connection = xo.createUserConnection(remoteAddress) connection.once('close', () => { socket.close() }) @@ -580,9 +573,6 @@ const setUpApi = (webServer, xo, config) => { // Close the XO connection with this WebSocket. socket.once('close', () => { - --n - log.info(`- WebSocket connection (${remoteAddress}) (${n} connected)`) - connection.close() }) diff --git a/packages/xo-server/src/xo.mjs b/packages/xo-server/src/xo.mjs index 958a1092f..d153cf8e1 100644 --- a/packages/xo-server/src/xo.mjs +++ b/packages/xo-server/src/xo.mjs @@ -40,8 +40,7 @@ export default class Xo extends EventEmitter { this._objects.createIndex('byRef', new XoUniqueIndex('_xapiRef')) // Connections to users. - this._nextConId = 0 - this._connections = { __proto__: null } + this._connections = new Set() this._httpRequestWatchers = { __proto__: null } @@ -125,17 +124,21 @@ export default class Xo extends EventEmitter { // ----------------------------------------------------------------- - createUserConnection() { + createUserConnection(remoteAddress) { const { _connections: connections } = this const connection = new Connection() - const id = (connection.id = this._nextConId++) + connection.set('user_ip', remoteAddress) - connections[id] = connection + connections.add(connection) connection.on('close', () => { - delete connections[id] + connections.delete(connection) + + log.info(`- WebSocket connection (${remoteAddress}) (${connections.size} connected)`) }) + log.info(`+ WebSocket connection (${remoteAddress}) (${connections.size} connected)`) + return connection } @@ -305,7 +308,7 @@ export default class Xo extends EventEmitter { return } - forEach(connections, connection => { + for (const connection of connections) { // Notifies only authenticated clients. if (connection.has('user_id') && connection.notify) { if (enteredMessage) { @@ -315,7 +318,7 @@ export default class Xo extends EventEmitter { connection.notify('all', exitedMessage) } } - }) + } reset() })