1 //Anonymous Chat Server2 //post a new message to the/chat address, or get the text or event stream from a URL in get form3 //Create a GET request to "/" to return a simple HTML file that includes the client chat UI4 5 varHTTP = require (' http ');6 7 //HTML files used by chat clients8 varClientui = require (' FS '). Readfilesync ("chatclient.html");9 varemulation = require (' FS '). Readfilesync ("Eventsourceemulation.js");Ten One //an array of Serverresponse objects to receive the sent events A varClients = []; - - //send a comment to the client every 20 seconds theSetInterval (function(){ -Clients.foreach (function(client) {Client.write (":p ing?n"))}); -}, 20000); - + //Create a new server - varServer =Newhttp. Server (); + A //when the server gets to a new request, run the callback function atServer.on ("Request",function(Request, response) { - //URL to parse request - varurl = require (' URL ')). Parse (request.url); - - //if "/", the server sends the client chat room UI - if(Url.pathname = = = "/"){ inResponse.writehead ($, {"Content-type": "Text/html"}); -Response.Write ("<script>" +emulation + "</script>"); to Response.Write (clientui); + Response.End (); - return; the } * //if it is an address other than "/chat", it returns 404 $ Else if(Url.pathname!== "/chat"){Panax NotoginsengResponse.writehead (404); - Response.End (); the return; + } A the //If the request type is post, then a client sends a new message + if(Request.method = = = "POST"){ -Request.setencoding ("UTF8"); $ varBODY = ""; $ //after the data has been fetched, it is added to the request body -Request.on ("Data",function(Chunk) {Body + =Chunk;}); - the //send an empty response when the request is complete -Request.on ("End",function(){WuyiResponse.writehead (200); the Response.End (); - Wumessage = ' data: ' +body.replace (' \ n ', ' \ndata: ') + ' \r\n\r\n '; - AboutClients.foreach (function(client) {client.write (message);}); $ - }); - } - //a client requests a set of messages A Else { +Response.writehead ($, {"Content-type": "Text/event-stream"}); theResponse.Write ("data:connected\n\n"); - $Request.connection.on ("End",function(){ theClients.splice (Clients.indexof (response), 1); the Response.End (); the }); the - //write down the response object in Clients.push (response); the } the About }); the the //Start the server the +Server.listen (8000); - the
Custom Server-sent Events Chat Server