varhttp=require('http');varfs=require('fs');//Array to contain active resourcesvarresources=newArray();http.createServer(function(req,res){if(req.headers.accept&&req.headers.accept=='text/event-stream'){if(req.url=='/events'){res.writeHead(200,{'Content-Type':'text/event-stream','Cache-Control':'no-cache','Connection':'keep-alive'});//Create a random ID for each guest in the chatroomres.chatID='guest'+Math.floor(Math.random()*1000);resources.push(res);//Remove from active chat resources if connection is closedreq.addListener('close',function(event){console.log('A connection was closed');varindex=resources.indexOf(res);if(index!=-1){resources.splice(index,1);}});}else{res.writeHead(404);res.end();}}else{if(req.method=="POST"&&req.url=='/xhr'){vardata='';req.addListener('data',function(chunk){data+=chunk;});req.addListener('end',function(){res.writeHead(200,{'Content-Type':'text/html'});res.write(data);res.end();//send the data to all the active chat resourcesfor(vari=0;i<resources.length;i++){constructSSE(resources[i],2,[resources[i].chatID,data]);}});}else{res.writeHead(200,{'Content-Type':'text/html'});res.write(fs.readFileSync(__dirname+'/sse-node.html'));res.end();}}}).listen(8000);functionconstructSSE(res,id,data){res.write('id: '+id+'n');//Adds the capability to send multiple lines of data if they are in an arrayif(data.constructor!=Array)data=[data];for(vari=0;i<data.length;i++)res.write("data: "+data[i]+'n');res.write('n');}