socket.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. define(function () {
  2. function Socket(params) {
  3. this.params = params;
  4. this.url = (window.location.protocol === 'http:' ? 'ws' : 'wss') + '://' + window.location.hostname;
  5. this.port = params.port || '';
  6. this.params = '';
  7. if (params.params.constructor.toString().indexOf('Object') !== -1) {
  8. // for (var key in params.params) {
  9. // if (Object.hasOwnProperty.call(params.params, key)) {
  10. // this.params += (this.params ? '&' : '') + key + '=' + params.params[key];
  11. // }
  12. // }
  13. this.params = Object.keys(params.params).map(function (key) {
  14. return key + '=' + params.params[key];
  15. }).join('&');
  16. }
  17. this.connect(params);
  18. }
  19. Socket.prototype.connect = function (params) {
  20. var self = this;
  21. this.ws = new WebSocket(this.url + (this.port ? ':' + this.port : '') + (this.params ? '?' + this.params : ''));
  22. this.ws.onopen = function () {
  23. self.heartbeat();
  24. if (typeof params.onopen === 'function') {
  25. params.onopen();
  26. }
  27. };
  28. this.ws.onmessage = function (event) {
  29. var data = JSON.parse(event.data);
  30. self.heartbeat();
  31. if (typeof params.onmessage === 'function') {
  32. params.onmessage(data);
  33. }
  34. };
  35. this.ws.onclose = function () {
  36. self.connect(self.params);
  37. if (typeof params.onclose === 'function') {
  38. params.onclose();
  39. }
  40. };
  41. this.ws.onerror = function () {
  42. };
  43. };
  44. Socket.prototype.heartbeat = function () {
  45. var self = this;
  46. clearTimeout(this.timeoutId);
  47. this.timeoutId = setTimeout(function () {
  48. self.send({
  49. type: 'ping'
  50. });
  51. }, 3000);
  52. };
  53. Socket.prototype.send = function (params) {
  54. if (this.ws.readyState === 1) {
  55. this.ws.send(typeof params === 'string' ? params : JSON.stringify(params));
  56. }
  57. };
  58. Socket.prototype.close = function (params) {
  59. this.ws.close();
  60. };
  61. return Socket;
  62. });