diff --git a/src/app.ts b/src/app.ts index 4e64935..ab87a61 100644 --- a/src/app.ts +++ b/src/app.ts @@ -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'); } diff --git a/src/coordinates.ts b/src/coordinates.ts new file mode 100644 index 0000000..f8cceec --- /dev/null +++ b/src/coordinates.ts @@ -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; + } +}