You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sockets.js 2.2KB

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