Browse Source

some fixes

Ivan Asmer 6 years ago
parent
commit
cf4f9d26f3
2 changed files with 17 additions and 17 deletions
  1. 13 14
      index.js
  2. 4 3
      public/index.js

+ 13 - 14
index.js

@@ -12,7 +12,6 @@ const wss = new WebSocket.Server({ server });
 
 const messages = [];
 var   sockets  = [];
-let   userCount = 0;
 
 
 
@@ -30,7 +29,7 @@ function noPromise(){
     return np
 }
 
-function asynchronize({s, chunkEventName, endEventName}){
+function asynchronize({s, chunkEventName="message", endEventName="close"}){
     return function*(){
         const chunks        = {};
         const promises      = {};
@@ -67,9 +66,10 @@ function asynchronize({s, chunkEventName, endEventName}){
                 p.resolve(chunks[promiseCount])
                 clear(promiseCount)
             }
-
-            promises[promiseCount] = p;
-            promiseCount++
+            else {
+                promises[promiseCount] = p;
+                promiseCount++
+            }
 
             yield p;
         }
@@ -81,10 +81,10 @@ function asynchronize({s, chunkEventName, endEventName}){
 
 
 
-function broadcast(wtf){
+function broadcast(data){
     for (s of sockets){
-        console.log(wtf)
-        s.send(JSON.stringify(wtf))
+        console.log(data)
+        s.send(JSON.stringify(data))
     }
 }
 
@@ -101,7 +101,7 @@ let RPC = {
     },
 
     getUserCount(){
-        return userCount;
+        return sockets.length;
     }
 }
 
@@ -111,12 +111,12 @@ let RPC = {
 
 wss.on('connection', async ws => {
 
-    let gena = asynchronize({s:ws, chunkEventName: 'message', endEventName: 'close'})
+    let gena = asynchronize({s:ws})
 
     sockets.push(ws)
 
-    userCount++;
-    broadcast({func:'getUserCount', value: userCount})
+    broadcast({func:'getUserCount', value: sockets.length})
+
     for (let p of gena()){
         try {
             let message = await p;
@@ -137,8 +137,7 @@ wss.on('connection', async ws => {
 
     sockets = sockets.filter(s => s !== ws)
 
-    userCount--;
-    broadcast({func:'getUserCount', value: userCount})
+    broadcast({func:'getUserCount', value: sockets.length})
 });
 
 app.use(express.static('public'));

+ 4 - 3
public/index.js

@@ -54,9 +54,10 @@ function asynchronize({s, chunkEventName, endEventName}){
                 p.resolve(chunks[promiseCount])
                 clear(promiseCount)
             }
-
-            promises[promiseCount] = p;
-            promiseCount++
+            else {
+                promises[promiseCount] = p;
+                promiseCount++
+            }
 
             yield p;
         }