chat.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // +----------------------------------------------------------------------
  2. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  3. // +----------------------------------------------------------------------
  4. // | Copyright (c) 2016~2022 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. console.log('创建连接了!')
  41. this.send({
  42. type: "login",
  43. data: $store.state.app.token
  44. });
  45. this.vm.$emit("socket_open");
  46. },
  47. init() {
  48. var that = this;
  49. this.timer = setInterval(()=> {
  50. that.send({
  51. type: "ping"
  52. });
  53. }, 10000);
  54. },
  55. send(data) {
  56. return this.ws.send(JSON.stringify(data));
  57. },
  58. onMessage(res) {
  59. const {
  60. type,
  61. data = {}
  62. } = JSON.parse(res.data);
  63. this.vm.$emit(type, data);
  64. },
  65. onClose: function() {
  66. clearInterval(this.timer);
  67. },
  68. onError: function(e) {
  69. this.vm.$emit("socket_error", e);
  70. }
  71. };
  72. Socket.prototype.constructor = Socket;
  73. export default Socket;