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

sockets.js 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. var iolib = require('socket.io')
  2. , path = require("path")
  3. , fs = require('fs')
  4. , BoardData = require("./boardData.js").BoardData;
  5. var boards = {
  6. "anonymous" : {
  7. "data" : new BoardData(),
  8. }
  9. };
  10. var boardName = "anonymous";
  11. function startIO(app) {
  12. io = iolib.listen(app);
  13. //Default configuration
  14. //io.enable('browser client minification'); // send minified client
  15. io.enable('browser client etag'); // apply etag caching logic based on version number
  16. io.enable('browser client gzip'); // gzip the file
  17. io.set('log level', 1); // reduce logging
  18. // enable all transports
  19. io.set('transports', ['websocket', 'flashsocket', 'htmlfile', 'xhr-polling', 'jsonp-polling']);
  20. io.sockets.on('connection', socketConnection);
  21. return io;
  22. }
  23. function socketConnection (socket) {
  24. socket.on("getboard", function() {
  25. //Send all previously broadcasted data
  26. boards[boardName].data.getAll(function(data) {
  27. socket.emit("broadcast", data);
  28. });
  29. });
  30. socket.on('broadcast', function (data) {
  31. //Send data to all other connected users
  32. socket.broadcast.emit('broadcast', data);
  33. //Use setTimeout in order to be sure that the message is broadcasted
  34. // as soon as possible (before we do anything else on the server side)
  35. saveHistory(data);
  36. });
  37. }
  38. function saveHistory(message) {
  39. var id = message.id;
  40. var boardData = boards[boardName].data;
  41. switch (message.type) {
  42. case "delete":
  43. if (id) boardData.delete(id);
  44. break;
  45. case "update":
  46. delete message.type;
  47. if (id) boardData.update(id, message);
  48. break;
  49. case "child":
  50. boardData.addChild(message.parent, message);
  51. break;
  52. default: //Add data
  53. if (!id) console.error("Invalid message: ", message);
  54. else boardData.set(id, message);
  55. }
  56. }
  57. function generateUID (prefix, suffix) {
  58. var uid = Date.now().toString(36); //Create the uids in chronological order
  59. uid += (Math.round(Math.random()*36)).toString(36); //Add a random character at the end
  60. if (prefix) uid = prefix + uid;
  61. if (suffix) uid = uid + suffix;
  62. return uid;
  63. }
  64. if (exports) {
  65. exports.start = function(app) {
  66. boards[boardName].data.on("ready", function() {
  67. startIO(app);
  68. });
  69. };
  70. }