Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

sockets.js 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. var iolib = require('socket.io')
  2. , path = require("path")
  3. , fs = require('fs');
  4. /**
  5. * Name of the file the persistent data will be written to
  6. * if there are more messages, older ones will be erased
  7. * @const
  8. * @type {string}
  9. */
  10. var HISTORY_FILE = path.join(__dirname, "../server-data/history.txt");
  11. /**
  12. * Number of messages to keep in memory
  13. * if there are more messages, older ones will be erased
  14. * @const
  15. * @type {number}
  16. */
  17. var MAX_HISTORY_LENGTH = 1e5;
  18. var history = [],
  19. unsaved_history = [];
  20. //Load existing history
  21. fs.readFile(HISTORY_FILE, 'utf8', function (file_err, history_str) {
  22. if (file_err) {
  23. if (file_err.code == "ENOENT") {
  24. console.log("History file not found. It will be created.");
  25. } else {
  26. console.log("An error occured while trying to open history file: "+file_err);
  27. }
  28. }else {
  29. try {
  30. history = history_str
  31. .split("\n")
  32. .slice(-MAX_HISTORY_LENGTH)
  33. .filter(function(line){return line && line[0]!="#"})
  34. .map(JSON.parse);
  35. } catch(json_err) {
  36. console.log("Bad history file: "+json_err);
  37. }
  38. }
  39. });
  40. function socketConnection (socket) {
  41. //On the first connection, send all previously broadcasted data
  42. for (var i=0;i<history.length;i++){
  43. socket.emit("broadcast", history[i]);
  44. }
  45. socket.on('broadcast', function (data) {
  46. //Send data to all other connected users
  47. socket.broadcast.emit('broadcast', data);
  48. addHistory(data);
  49. });
  50. }
  51. function addHistory(data) {
  52. //Save the data in memory
  53. history.push(data);
  54. unsaved_history.push(data);
  55. //Avoid a memory overload
  56. if (history.length > MAX_HISTORY_LENGTH) {
  57. history.pop();
  58. }
  59. }
  60. setInterval(function(){
  61. if (unsaved_history.length > 0) {
  62. fs.open(HISTORY_FILE, 'a', function (err, fd){
  63. if (err) console.error("Unable to save history:", err);
  64. else {
  65. var tobesaved = unsaved_history;
  66. unsaved_history = [];
  67. var data_str = "";
  68. data_str += tobesaved
  69. .map(JSON.stringify)
  70. .join("\n");
  71. data_str += "\n#" + (new Date()).toString() + "\n";
  72. fs.write(fd, data_str);
  73. fs.close(fd);
  74. }
  75. });
  76. }
  77. }, 10*1000);
  78. if (exports) {
  79. exports.start = function(app){
  80. io = iolib.listen(app, {'log':false});
  81. io.sockets.on('connection', socketConnection);
  82. return io;
  83. };
  84. exports.HISTORY_FILE = HISTORY_FILE;
  85. }