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.
 
 
 

86 lines
1.9 KiB

  1. define([
  2. 'socket',
  3. 'js/system/events'
  4. ], function (
  5. io,
  6. events
  7. ) {
  8. let client = {
  9. doneConnect: false,
  10. init: function (onReady) {
  11. let tType = 'websocket';
  12. if (window.location.href.indexOf('polling') > -1)
  13. tType = 'polling';
  14. this.socket = io({
  15. transports: [tType]
  16. });
  17. this.socket.on('connect', this.onConnected.bind(this, onReady));
  18. this.socket.on('handshake', this.onHandshake.bind(this));
  19. this.socket.on('event', this.onEvent.bind(this));
  20. this.socket.on('events', this.onEvents.bind(this));
  21. this.socket.on('dc', this.onDisconnect.bind(this));
  22. },
  23. onConnected: function (onReady) {
  24. if (this.doneConnect)
  25. this.onDisconnect();
  26. else
  27. this.doneConnect = true;
  28. if (onReady)
  29. onReady();
  30. },
  31. onDisconnect: function () {
  32. window.location = window.location;
  33. },
  34. onHandshake: function () {
  35. events.emit('onHandshake');
  36. this.socket.emit('handshake');
  37. },
  38. request: function (msg) {
  39. this.socket.emit('request', msg, msg.callback);
  40. },
  41. onEvent: function (response) {
  42. events.emit(response.event, response.data);
  43. },
  44. onEvents: function (response) {
  45. //If we get objects, self needs to be first
  46. // otherwise we might create the object (setting his position or attack animation)
  47. // before instantiating it
  48. let oList = response.onGetObject;
  49. if (oList) {
  50. let prepend = oList.filter(function (o) {
  51. return o.self;
  52. });
  53. oList.spliceWhere(function (o) {
  54. return prepend.some(function (p) {
  55. return p == o;
  56. });
  57. });
  58. oList.unshift.apply(oList, prepend);
  59. }
  60. for (var e in response) {
  61. let r = response[e];
  62. //Certain messages expect to be performed last (because the object they act on hasn't been greated when they get queued)
  63. r.sort(function (a, b) {
  64. if (a.performLast)
  65. return 1;
  66. else if (b.performLast)
  67. return -1;
  68. return 0;
  69. });
  70. r.forEach(function (o) {
  71. events.emit(e, o);
  72. });
  73. }
  74. }
  75. };
  76. return client;
  77. });