File size: 1,080 Bytes
72c8f1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// server.js on glitch

const WebSocketServer = require("uws").Server
const wss = new WebSocketServer({port: process.env.PORT})
var connections = {};

wss.on('connection', (ws) => {
  ws.on('close', function() {
    Object.keys(connections).forEach(function (key) {
      if (connections[key] === ws) {
        delete connections[key];
      }
    });
  });
  ws.on('message', function(json) {

    var data = JSON.parse(json);
    if (data.action == 'connect') {
      if (!connections[data.conn_id]) {
        connections[data.conn_id] = [];
      }
      connections[data.conn_id].push(ws);
    } else if (data.action == 'predict') {
      if (data.conn_id) {
        var conns = connections[data.conn_id];
        if (conns && conns.length > 0) {
          for(let i = 0; i < conns.length; i++) {
            if (conns[i]) {
              conns[i].send(JSON.stringify({action: 'predict', value: data.value, label: data.label}));
            }
          }
        }
      }
    }
  });
});

wss.on('error', (error) => {
  throw error
})