您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

sockets.js 3.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. var iolib = require('socket.io')
  2. , log = require("./log.js").log
  3. , BoardData = require("./boardData.js").BoardData;
  4. var MAX_EMIT_COUNT = 64; // Maximum number of draw operations before getting banned
  5. var MAX_EMIT_COUNT_PERIOD = 5000; // Duration (in ms) after which the emit count is reset
  6. // Map from name to *promises* of BoardData
  7. var boards = {};
  8. function noFail(fn) {
  9. return function noFailWrapped(arg) {
  10. try {
  11. return fn(arg);
  12. } catch (e) {
  13. console.trace(e);
  14. }
  15. }
  16. }
  17. function startIO(app) {
  18. io = iolib(app);
  19. io.on('connection', noFail(socketConnection));
  20. return io;
  21. }
  22. /** Returns a promise to a BoardData with the given name*/
  23. function getBoard(name) {
  24. if (boards.hasOwnProperty(name)) {
  25. return boards[name];
  26. } else {
  27. var board = BoardData.load(name);
  28. boards[name] = board;
  29. return board;
  30. }
  31. }
  32. function socketConnection(socket) {
  33. function joinBoard(name) {
  34. // Default to the public board
  35. if (!name) name = "anonymous";
  36. // Join the board
  37. socket.join(name);
  38. return getBoard(name).then(board => {
  39. board.users.add(socket.id);
  40. log('board joined', { 'board': board.name, 'users': board.users.size });
  41. return board;
  42. });
  43. }
  44. socket.on("getboard", noFail(function onGetBoard(name) {
  45. joinBoard(name).then(board => {
  46. //Send all the board's data as soon as it's loaded
  47. socket.emit("broadcast", { _children: board.getAll() });
  48. });
  49. }));
  50. socket.on("joinboard", noFail(joinBoard));
  51. var lastEmitSecond = Date.now() / MAX_EMIT_COUNT_PERIOD | 0;
  52. var emitCount = 0;
  53. socket.on('broadcast', noFail(function onBroadcast(message) {
  54. var currentSecond = Date.now() / MAX_EMIT_COUNT_PERIOD | 0;
  55. if (currentSecond === lastEmitSecond) {
  56. emitCount++;
  57. if (emitCount > MAX_EMIT_COUNT) {
  58. var request = socket.client.request;
  59. log('BANNED', {
  60. user_agent: request.headers['user-agent'],
  61. original_ip: request.headers['x-forwarded-for'] || request.headers['forwarded'],
  62. emit_count: emitCount
  63. });
  64. return;
  65. }
  66. } else {
  67. emitCount = 0;
  68. lastEmitSecond = currentSecond;
  69. }
  70. var boardName = message.board || "anonymous";
  71. var data = message.data;
  72. if (!socket.rooms.hasOwnProperty(boardName)) socket.join(boardName);
  73. if (!data) {
  74. console.warn("Received invalid message: %s.", JSON.stringify(message));
  75. return;
  76. }
  77. //Send data to all other users connected on the same board
  78. socket.broadcast.to(boardName).emit('broadcast', data);
  79. // Save the message in the board
  80. saveHistory(boardName, data);
  81. }));
  82. socket.on('disconnecting', function onDisconnecting(reason) {
  83. Object.keys(socket.rooms).forEach(function disconnectFrom(room) {
  84. if (boards.hasOwnProperty(room)) {
  85. boards[room].then(board => {
  86. board.users.delete(socket.id);
  87. var userCount = board.users.size;
  88. log('disconnection', { 'board': board.name, 'users': board.users.size });
  89. if (userCount === 0) {
  90. board.save();
  91. delete boards[room];
  92. }
  93. });
  94. }
  95. });
  96. });
  97. }
  98. function saveHistory(boardName, message) {
  99. var id = message.id;
  100. getBoard(boardName).then(board => {
  101. switch (message.type) {
  102. case "delete":
  103. if (id) board.delete(id);
  104. break;
  105. case "update":
  106. delete message.type;
  107. if (id) board.update(id, message);
  108. break;
  109. case "child":
  110. board.addChild(message.parent, message);
  111. break;
  112. default: //Add data
  113. if (!id) throw new Error("Invalid message: ", message);
  114. board.set(id, message);
  115. }
  116. });
  117. }
  118. function generateUID(prefix, suffix) {
  119. var uid = Date.now().toString(36); //Create the uids in chronological order
  120. uid += (Math.round(Math.random() * 36)).toString(36); //Add a random character at the end
  121. if (prefix) uid = prefix + uid;
  122. if (suffix) uid = uid + suffix;
  123. return uid;
  124. }
  125. if (exports) {
  126. exports.start = startIO;
  127. }