Ivan Asmer vor 6 Jahren
Ursprung
Commit
b65d9d422b
2 geänderte Dateien mit 46 neuen und 2 gelöschten Zeilen
  1. 1 1
      index.js
  2. 45 1
      public/index.js

+ 1 - 1
index.js

@@ -11,7 +11,7 @@ const server = http.createServer(app);
 const wss = new WebSocket.Server({ server });
 
 const messages = [];
-const sockets  = [];
+var   sockets  = [];
 let   userCount = 0;
 
 

+ 45 - 1
public/index.js

@@ -10,7 +10,7 @@ function noPromise(){
 }
 
 function asynchronize({s, chunkEventName, endEventName}){
-    return function* wrapper(){
+    return async function* wrapper(){
         const chunks        = {};
         const promises      = {};
 
@@ -21,6 +21,12 @@ function asynchronize({s, chunkEventName, endEventName}){
         let   promiseCount  = 0;
         let   end           = false;
 
+        if (!('on' in s)){
+            s.on = function(eventName, callback){
+                this['on' + eventName] = callback;
+            }
+        }
+
         s.on(chunkEventName, data => {
             chunks[chunkCount] = data
 
@@ -54,3 +60,41 @@ function asynchronize({s, chunkEventName, endEventName}){
         }
     }
 }
+
+function msg2dom({nick, message, timestamp}){
+    const div = document.createElement('div')
+    div.innerHTML = `<b>${nick}<b>:${message}`
+    return div;
+}
+
+let RPC = {
+    addMessage(data){
+        chat.appendChild(msg2dom(data))
+    },
+
+    getMessages({offset=0}){
+        return messages.slice(offset)
+    },
+
+    getUserCount(){
+        return userCount;
+    }
+}
+
+
+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)
+        }
+    }
+})()
+
+
+send.onclick = function(){
+    socket.send(JSON.stringify({func: 'addMessage', nick: nick.value, message: msg.value}))
+}