Changes for live preview - process every coordinate

This commit is contained in:
Robin Steinberg 2021-08-25 22:57:41 +02:00
parent 2f9fbe3ff9
commit 3e62154f0e
2 changed files with 48 additions and 8 deletions

View File

@ -1,10 +1,13 @@
import WebSocket from 'ws';
import Coordinates from './coordinates';
const wss = new WebSocket.Server({ port: 8081 });
const receivers: WebSocket[] = [];
let sender: WebSocket | null = null;
const paths = [] as string[];
const paths = [] as Coordinates[][];
let currentPath = [] as Coordinates[];
wss.on('connection', ws => {
console.log('CONNECTION incoming');
@ -18,7 +21,7 @@ wss.on('connection', ws => {
addReceiver(ws)
break;
default:
paths.push(str);
console.log('Unknown register code: ' + str);
break;
}
});
@ -29,8 +32,11 @@ console.log('READY');
function addReceiver(ws: WebSocket) {
console.log('RECEIVER registered');
for (const path of paths) {
ws.send(path);
ws.send('START');
path.forEach(c => ws.send(JSON.stringify(c)));
ws.send('STOP');
}
receivers.push(ws);
ws.onclose = () => {
@ -56,16 +62,41 @@ function setSender(ws: WebSocket) {
}
function processMessage(message: WebSocket.Data) {
const path = message.toString();
console.log('PATH RECEIVED: ' + path);
paths.push(path);
const text = message.toString();
switch (text) {
case 'START':
startPath();
break;
case 'STOP':
finishPath();
break;
default:
processCoordinates(text);
break;
}
}
function processCoordinates(text: string) {
console.log('COORDINATES received: ' + text);
console.log('SENDING to ' + receivers.length, 'clients');
receivers.forEach(r => r.send(path));
receivers.forEach(r => r.send(text));
currentPath.push(JSON.parse(text));
}
function startPath() {
currentPath = [];
receivers.forEach(r => r.send('START'));
}
function finishPath() {
paths.push(currentPath);
receivers.forEach(r => r.send("STOP"));
}
function clearPaths() {
paths.splice(0, paths.length);
receivers.forEach(r => r.send("CLEAR"));
receivers.forEach(r => r.send('CLEAR'));
console.log('Paths have been cleared');
}

9
src/coordinates.ts Normal file
View File

@ -0,0 +1,9 @@
export default class Coordinates {
public x: number;
public y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}