server.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. //to chat: http://js.do/code/flexichat
  2. http = require('http');
  3. var history = [];
  4. var messageId = 0;
  5. var RPCFuncs = {
  6. getMessages: function(data){
  7. var messageId = +data.messageId;
  8. return history.slice(messageId);
  9. },
  10. addMessage: function(data){
  11. history.push(data);
  12. // return history.length;
  13. }
  14. };
  15. server = http.createServer(function(req, res){
  16. if (req.method == "POST"){
  17. var body = '';
  18. req.on('data', function (data) {
  19. body += data;
  20. });
  21. req.on('end', function () {
  22. console.log("Body: " + body);
  23. data = JSON.parse(body);
  24. var timestamp =(new Date()).getTime();
  25. if ("func" in data){
  26. if (data.func in RPCFuncs){
  27. var func = data.func;
  28. delete data.func;
  29. data.timestamp = timestamp;
  30. var result = {data: RPCFuncs[func](data), nextMessageId: history.length};
  31. console.log("answer on request:");
  32. console.log(JSON.stringify(result));
  33. res.end(JSON.stringify(result));
  34. }
  35. else {
  36. console.log("no func in functions array" + body);
  37. }
  38. }
  39. else {
  40. console.log("no func key in data:" + body);
  41. }
  42. //if (!("messageId" in message) || (Object.keys(message).length > 1)){
  43. //message.timestamp = timestamp;
  44. //history[messageId] = message;
  45. //messageId++;
  46. //}
  47. //if ("messageId" in message){
  48. //messages = history.slice(+message.messageId);
  49. //res.end(JSON.stringify({timestamp: timestamp, messageId: messageId, messages: messages}))
  50. //console.log({timestamp: timestamp, messageId: messageId, messages: messages})
  51. //}
  52. //else {
  53. //res.end(JSON.stringify({timestamp: timestamp, messageId: messageId}))
  54. //console.log({timestamp: timestamp, messageId: messageId})
  55. //}
  56. });
  57. res.setHeader('Access-Control-Allow-Origin', '*');
  58. res.setHeader('Access-Control-Request-Method', '*');
  59. res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, POST');
  60. res.setHeader('Access-Control-Allow-Headers', '*');
  61. res.writeHead(200, {'Content-Type': 'text/json'});
  62. //res.end('post received');
  63. }
  64. });
  65. port = 8070;
  66. host = '164.138.30.21';
  67. server.listen(port, host);
  68. console.log("Listen...");