فهرست منبع

WIP: get clients count

Yuki Takei 5 سال پیش
والد
کامیت
468e1414b6
2فایلهای تغییر یافته به همراه41 افزوده شده و 1 حذف شده
  1. 1 1
      src/server/crowi/index.js
  2. 40 0
      src/server/service/socket-io.js

+ 1 - 1
src/server/crowi/index.js

@@ -278,7 +278,7 @@ Crowi.prototype.setupS2sMessagingService = async function() {
 Crowi.prototype.setupSocketIoService = async function() {
   const SocketIoService = require('../service/socket-io');
   if (this.socketIoService == null) {
-    this.socketIoService = new SocketIoService();
+    this.socketIoService = new SocketIoService(this.configManager);
   }
 };
 

+ 40 - 0
src/server/service/socket-io.js

@@ -5,6 +5,14 @@ const socketIo = require('socket.io');
  */
 class SocketIoService {
 
+  constructor(configManager) {
+    this.configManager = configManager;
+
+    this.connectionsCount = 0;
+    this.connectionsCountForAdmin = 0;
+    this.connectionsCountForGuest = 0;
+  }
+
   get isInitialized() {
     return (this.io != null);
   }
@@ -14,6 +22,8 @@ class SocketIoService {
       transports: ['websocket'],
     });
 
+    this.io.use(this.checkConnectionLimits.bind(this));
+
     // create namespace for admin
     this.adminNamespace = this.io.of('/admin');
   }
@@ -29,9 +39,39 @@ class SocketIoService {
     if (this.io == null) {
       throw new Error('Http server has not attached yet.');
     }
+
     return this.adminNamespace;
   }
 
+  async getClients(namespace) {
+    return new Promise((resolve, reject) => {
+      namespace.clients((error, clients) => {
+        if (error) {
+          reject(error);
+        }
+        resolve(clients);
+      });
+    });
+  }
+
+  /**
+   * @see https://socket.io/docs/server-api/#socket-client
+   */
+  async checkConnectionLimits(socket, next) {
+
+    const clients = await this.getClients(this.getDefaultSocket());
+    const adminClients = await this.getClients(this.getAdminSocket());
+
+    console.log('default', clients.length);
+    console.log('admin', adminClients.length);
+
+    if (socket.request.headers.cookie) {
+      console.log('cookie exists');
+      next();
+    }
+    // next(new Error('Authentication error'));
+  }
+
 }
 
 module.exports = SocketIoService;