server.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. //to chat: http://codepen.io/anon/pen/RoaJZG?editors=0010
  2. //http://js.do/code/flexichat
  3. http = require('http');
  4. var history = [];
  5. var messageId = 0;
  6. server = http.createServer(function(req, res){
  7. //console.dir(req);
  8. if (req.method == "POST"){
  9. var body = '';
  10. req.on('data', function (data) {
  11. body += data;
  12. });
  13. req.on('end', function () {
  14. console.log("Body: " + body);
  15. message = JSON.parse(body);
  16. var timestamp =(new Date()).getTime();
  17. if (!("messageId" in message) || (Object.keys(message).length > 1)){
  18. message.timestamp = timestamp;
  19. history[messageId] = message;
  20. messageId++;
  21. }
  22. if ("messageId" in message){
  23. messages = history.slice(+message.messageId);
  24. // console.log("slice: " + messages.length)
  25. res.end(JSON.stringify({timestamp: timestamp, messageId: messageId, messages: messages}))
  26. console.log({timestamp: timestamp, messageId: messageId, messages: messages})
  27. }
  28. else {
  29. res.end(JSON.stringify({timestamp: timestamp, messageId: messageId}))
  30. console.log({timestamp: timestamp, messageId: messageId})
  31. }
  32. });
  33. res.setHeader('Access-Control-Allow-Origin', '*');
  34. res.setHeader('Access-Control-Request-Method', '*');
  35. res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, POST');
  36. res.setHeader('Access-Control-Allow-Headers', '*');
  37. res.writeHead(200, {'Content-Type': 'text/json'});
  38. //res.end('post received');
  39. }
  40. });
  41. port = 8070;
  42. host = '164.138.30.21';
  43. server.listen(port, host);
  44. console.log("Listen...");