Sample Websockets Server

Overview


Sample Server



try{ const WebSocket = require('ws'); const wss = new WebSocket.Server({ port:8080}); wss.on('connection', (ws) => { function nextPrice(){ let lastPrice = prices[prices.length-1].price; let return1 = 0; [1,2,3,4,5,6,7,8,9,10].forEach(p=>{ return1 += 0.0002 + 2*Math.random(); }); return1 = return1/10; prices.push({price:lastPrice*return1}); } let prices = [{price:100}] for(let i=0;i<60;i++){ nextPrice(); } function timeout(){ let time = Math.random()*1000*5; setTimeout(function(){ nextPrice(); ws.send(JSON.stringify(prices)); timeout(); },time) } // Listen for messages from this client ws.on('message', (message) => { ws.send(JSON.stringify(prices)); timeout(); }); // Handle client disconnection ws.on('close', () => {}); }); } catch(err){ console.log(err.toString()) }