server.js 2.5 KB

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