Browse Source

user count

Ivan Asmer 6 years ago
parent
commit
a7f919c0c5
2 changed files with 23 additions and 11 deletions
  1. 2 0
      index.js
  2. 21 11
      public/index.js

+ 2 - 0
index.js

@@ -116,6 +116,7 @@ wss.on('connection', async ws => {
     sockets.push(ws)
 
     userCount++;
+    broadcast({func:'getUserCount', value: userCount})
     for (let p of gena()){
         try {
             let message = await p;
@@ -137,6 +138,7 @@ wss.on('connection', async ws => {
     sockets = sockets.filter(s => s !== ws)
 
     userCount--;
+    broadcast({func:'getUserCount', value: userCount})
 });
 
 app.use(express.static('public'));

+ 21 - 11
public/index.js

@@ -1,3 +1,5 @@
+let socket;
+
 function noPromise(){
     let resolve, reject;
 
@@ -72,25 +74,33 @@ let RPC = {
         chat.appendChild(msg2dom(data))
     },
 
-    //getUserCount(){
-        //return userCount;
-    //}
-}
+    getUserCount({value}){
+        chat.appendChild(msg2dom({nick: 'чатег', message: `${value} user online` , timestamp: (new Date()).getTime()}))
+    }
+};
 
 
-const socket = new WebSocket("ws://localhost:8999/");
-const aGena  = asynchronize({s: socket, chunkEventName: 'message', endEventName: 'close'});
 
 (async () => {
-    for await (let msg of aGena()){
-        let data = JSON.parse(msg.data)
-        if (data.func in RPC){
-            RPC[data.func](data)
+    while (true){
+        try{
+            socket = new WebSocket("ws://localhost:8999/");
+            let aGena  = asynchronize({s: socket, chunkEventName: 'message', endEventName: 'close'});
+            for await (let msg of aGena()){
+                let data = JSON.parse(msg.data)
+                if (data.func in RPC){
+                    RPC[data.func](data)
+                }
+            }
+        } 
+        catch (e){
+            console.log(e)
         }
     }
 })()
 
 
 send.onclick = function(){
-    socket.send(JSON.stringify({func: 'addMessage', nick: nick.value, message: msg.value}))
+    if (socket && typeof socket.send === 'function')
+        socket.send(JSON.stringify({func: 'addMessage', nick: nick.value, message: msg.value}))
 }