sockets.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. "use strict";
  2. var socket = require("socket.io");
  3. var utils = require("./server/utils");
  4. /**
  5. * Plugin interface
  6. * @returns {*|function(this:exports)}
  7. */
  8. module.exports.plugin = function (server, clientEvents, bs) {
  9. return exports.init(server, clientEvents, bs);
  10. };
  11. /**
  12. * @param {http.Server} server
  13. * @param clientEvents
  14. * @param {BrowserSync} bs
  15. */
  16. module.exports.init = function (server, clientEvents, bs) {
  17. var emitter = bs.events;
  18. var socketConfig = bs.options.get("socket").toJS();
  19. if (bs.options.get("mode") === "proxy" &&
  20. bs.options.getIn(["proxy", "ws"])) {
  21. server = utils.getServer(null, bs.options).server;
  22. server.listen(bs.options.getIn(["socket", "port"]));
  23. bs.registerCleanupTask(function () {
  24. server.close();
  25. });
  26. }
  27. var socketIoConfig = socketConfig.socketIoOptions;
  28. socketIoConfig.path = socketConfig.path;
  29. var io = socket(server, socketIoConfig);
  30. // Override default namespace.
  31. io.sockets = io.of(socketConfig.namespace);
  32. io.set("heartbeat interval", socketConfig.clients.heartbeatTimeout);
  33. /**
  34. * Listen for new connections
  35. */
  36. io.sockets.on("connection", handleConnection);
  37. /**
  38. * Handle each new connection
  39. * @param {Object} client
  40. */
  41. function handleConnection(client) {
  42. // set ghostmode callbacks
  43. if (bs.options.get("ghostMode")) {
  44. addGhostMode(client);
  45. }
  46. client.emit("connection", bs.options.toJS()); //todo - trim the amount of options sent to clients
  47. emitter.emit("client:connected", {
  48. ua: client.handshake.headers["user-agent"]
  49. });
  50. }
  51. /**
  52. * @param client
  53. */
  54. function addGhostMode(client) {
  55. clientEvents.forEach(addEvent);
  56. function addEvent(event) {
  57. client.on(event, function (data) {
  58. client.broadcast.emit(event, data);
  59. });
  60. }
  61. }
  62. return io;
  63. };
  64. //# sourceMappingURL=sockets.js.map