chat.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // +----------------------------------------------------------------------
  2. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  3. // +----------------------------------------------------------------------
  4. // | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
  5. // +----------------------------------------------------------------------
  6. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  7. // +----------------------------------------------------------------------
  8. // | Author: CRMEB Team <admin@crmeb.com>
  9. // +----------------------------------------------------------------------
  10. import $store from "@/store";
  11. import { VUE_APP_WS_URL } from "@/utils/index.js";
  12. const Socket = function() {
  13. this.ws = new WebSocket(wss(VUE_APP_WS_URL));
  14. this.ws.onopen = this.onOpen.bind(this);
  15. this.ws.onerror = this.onError.bind(this);
  16. this.ws.onmessage = this.onMessage.bind(this);
  17. this.ws.onclose = this.onClose.bind(this);
  18. };
  19. function wss(wsSocketUrl) {
  20. let ishttps = document.location.protocol == 'https:';
  21. if (ishttps) {
  22. return wsSocketUrl.replace('ws:', 'wss:');
  23. } else {
  24. return wsSocketUrl.replace('wss:', 'ws:');
  25. }
  26. }
  27. Socket.prototype = {
  28. vm(vm) {
  29. this.vm = vm;
  30. },
  31. close() {
  32. clearInterval(this.timer);
  33. this.ws.close();
  34. },
  35. onOpen: function() {
  36. console.log("ws open");
  37. this.init();
  38. this.send({
  39. type: "login",
  40. data: $store.state.app.token
  41. });
  42. this.vm.$emit("socket_open");
  43. },
  44. init: function() {
  45. var that = this;
  46. this.timer = setInterval(function() {
  47. that.send({ type: "ping" });
  48. }, 10000);
  49. },
  50. send: function(data) {
  51. return this.ws.send(JSON.stringify(data));
  52. },
  53. onMessage: function(res) {
  54. const { type, data = {} } = JSON.parse(res.data);
  55. this.vm.$emit(type, data);
  56. },
  57. onClose: function() {
  58. clearInterval(this.timer);
  59. },
  60. onError: function(e) {
  61. console.log(e);
  62. this.vm.$emit("socket_error", e);
  63. }
  64. };
  65. Socket.prototype.constructor = Socket;
  66. export default Socket;