chat.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // +----------------------------------------------------------------------
  2. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  3. // +----------------------------------------------------------------------
  4. // | Copyright (c) 2016~2025 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. this.ws = new WebSocket(wss(VUE_APP_WS_URL));
  16. this.ws.onopen = this.onOpen.bind(this);
  17. this.ws.onerror = this.onError.bind(this);
  18. this.ws.onmessage = this.onMessage.bind(this);
  19. this.ws.onclose = this.onClose.bind(this);
  20. };
  21. function wss(wsSocketUrl) {
  22. let ishttps = document.location.protocol == 'https:';
  23. if (ishttps) {
  24. return wsSocketUrl.replace('ws:', 'wss:');
  25. } else {
  26. return wsSocketUrl.replace('wss:', 'ws:');
  27. }
  28. }
  29. Socket.prototype = {
  30. vm(vm) {
  31. this.vm = vm;
  32. },
  33. close() {
  34. clearInterval(this.timer);
  35. this.ws.close();
  36. },
  37. onOpen: function() {
  38. console.log("ws open");
  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: function() {
  47. var that = this;
  48. this.timer = setInterval(function() {
  49. that.send({
  50. type: "ping"
  51. });
  52. }, 10000);
  53. },
  54. send: function(data) {
  55. return this.ws.send(JSON.stringify(data));
  56. },
  57. onMessage: function(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. console.log(e);
  69. this.vm.$emit("socket_error", e);
  70. }
  71. };
  72. Socket.prototype.constructor = Socket;
  73. export default Socket;