-
Notifications
You must be signed in to change notification settings - Fork 39
/
index.js
41 lines (36 loc) · 1.43 KB
/
index.js
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
const path = require('path');
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const app = express();
const httpServer = http.createServer(app);
const PORT = process.env.PORT || 3000;
const wsServer = new WebSocket.Server({ server: httpServer });
// array of connected websocket clients
let connectedClients = [];
wsServer.on('connection', (ws, req) => {
console.log('Connected');
// add new connected client
connectedClients.push(ws);
// listen for messages from the streamer, the clients will not send anything so we don't need to filter
ws.on('message', data => {
// send the base64 encoded frame to each connected ws
connectedClients.forEach((ws, i) => {
if (ws.readyState === ws.OPEN) { // check if it is still connected
ws.send(data); // send
} else { // if it's not connected remove from the array of connected ws
connectedClients.splice(i, 1);
}
});
});
});
// HTTP stuff
app.get('/client', (req, res) => res.sendFile(path.resolve(__dirname, './client.html')));
app.get('/streamer', (req, res) => res.sendFile(path.resolve(__dirname, './streamer.html')));
app.get('/', (req, res) => {
res.send(`
<a href="streamer">Streamer</a><br>
<a href="client">Client</a>
`);
});
httpServer.listen(PORT, () => console.log(`HTTP server listening at http://localhost:${PORT}`));