import ws from 'ws' import { v4 } from 'uuid' let wss = null const connections = {} export const sub = [] let overlayStream = null export const state = (data) => { overlayStream = data } export const start = () => { console.warn('WS SERVER STARTED.') wss = new ws.Server({ port: 8001, }) wss.on('connection', handle) } export const stop = () => { Object.keys(connections).forEach((k) => { delete connections[k] }) wss.close(() => { wss = null }) console.warn('WS SERVER CLOSED') } export const status = () => { if (wss !== null) return true return false } export const sendAll = () => { Object.values(connections).forEach(v => { sendData(v) }) } const handle = (w) => { console.warn('NEW WS CONNECTION') const id = v4() connections[id] = w sendData(w) w.on('message', msg => onMsg(msg, id)) w.on('close', () => { delete connections[id] }) } const onMsg = (msg, id) => { const d = JSON.parse(msg) if (d.hasOwnProperty('event')) { if (d.event === 'read') { sendData(connections[id]) } else if (d.event === 'update') { console.warn('RECEIVED UPDATE') sub.forEach(x => { x(d.data) }) } } } const sendData = (w) => { console.log('SENDING DATA') if (overlayStream !== null) { console.log(overlayStream) w.send(JSON.stringify({ event: 'read', data: overlayStream, })) } }