chat.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // +----------------------------------------------------------------------
  2. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  3. // +----------------------------------------------------------------------
  4. // | Copyright (c) 2016~2023 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 {
  12. VUE_APP_WS_URL
  13. } from "@/utils/index.js";
  14. const Socket = function() {
  15. let url = VUE_APP_WS_URL
  16. this.ws = new WebSocket(wss(url));
  17. this.ws.onopen = this.onOpen.bind(this);
  18. this.ws.onerror = this.onError.bind(this);
  19. this.ws.onmessage = this.onMessage.bind(this);
  20. this.ws.onclose = this.onClose.bind(this);
  21. };
  22. function wss(wsSocketUrl) {
  23. let ishttps = document.location.protocol == 'https:';
  24. if (ishttps) {
  25. return wsSocketUrl.replace('ws:', 'wss:');
  26. } else {
  27. return wsSocketUrl.replace('wss:', 'ws:');
  28. }
  29. }
  30. Socket.prototype = {
  31. vm(vm) {
  32. this.vm = vm;
  33. },
  34. close() {
  35. clearInterval(this.timer);
  36. this.ws.close();
  37. },
  38. onOpen() {
  39. this.init();
  40. this.send({
  41. type: "login",
  42. data: $store.state.app.token
  43. });
  44. this.vm.$emit("socket_open");
  45. },
  46. init() {
  47. var that = this;
  48. this.timer = setInterval(()=> {
  49. that.send({
  50. type: "ping"
  51. });
  52. }, 10000);
  53. },
  54. send(data) {
  55. return this.ws.send(JSON.stringify(data));
  56. },
  57. onMessage(res) {
  58. const {
  59. type,
  60. data = {}
  61. } = JSON.parse(res.data);
  62. this.vm.$emit(type, data);
  63. },
  64. onClose: function() {
  65. clearInterval(this.timer);
  66. },
  67. onError: function(e) {
  68. this.vm.$emit("socket_error", e);
  69. }
  70. };
  71. Socket.prototype.constructor = Socket;
  72. export default Socket;