chat.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // +----------------------------------------------------------------------
  2. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  3. // +----------------------------------------------------------------------
  4. // | Copyright (c) 2016~2024 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. HTTP_REQUEST_URL,
  13. VUE_APP_WS_URL
  14. } from "@/config/app.js";
  15. const Socket = function() {
  16. let wsUrl = `${VUE_APP_WS_URL}&token=${$store.state.app.token}`
  17. this.ws = uni.connectSocket({
  18. // #ifdef H5
  19. url:wss(wsUrl),
  20. // #endif
  21. // #ifdef MP || APP-PLUS
  22. url:wsUrl,
  23. // #endif
  24. header: {
  25. 'content-type': 'application/json'
  26. },
  27. method: 'GET',
  28. success: (res) => {
  29. console.log(res, 'success');
  30. }
  31. });
  32. this.ws.onOpen(this.onSocketOpen.bind(this))
  33. this.ws.onError(this.onError.bind(this));
  34. this.ws.onMessage(this.onMessage.bind(this))
  35. this.ws.onClose(this.onClose.bind(this));
  36. // this.ws.close(this.close.bind(this));
  37. };
  38. // #ifdef H5
  39. function wss(wsSocketUrl) {
  40. let ishttps = document.location.protocol == 'https:';
  41. if (ishttps) {
  42. return wsSocketUrl.replace('ws:', 'wss:');
  43. } else {
  44. return wsSocketUrl.replace('wss:', 'ws:');
  45. }
  46. }
  47. // #endif
  48. Socket.prototype = {
  49. // close() {
  50. // clearInterval(this.timer);
  51. // this.ws.close();
  52. // },
  53. onSocketOpen: function(my) {
  54. this.init();
  55. uni.$emit("socket_open");
  56. },
  57. init: function() {
  58. var that = this;
  59. this.timer = setInterval(function() {
  60. that.send({
  61. type: "ping"
  62. });
  63. }, 10000);
  64. },
  65. send: function(data) {
  66. let datas = JSON.stringify(data)
  67. return uni.sendSocketMessage({
  68. data: datas
  69. });
  70. },
  71. onMessage: function(res) {
  72. console.log(JSON.parse(res.data), 'onMessage')
  73. const {
  74. type,
  75. data = {}
  76. } = JSON.parse(res.data);
  77. uni.$emit(type, data)
  78. },
  79. onClose: function() {
  80. uni.closeSocket();
  81. clearInterval(this.timer);
  82. uni.$emit("socket_close");
  83. },
  84. onError: function(e) {
  85. console.log(e);
  86. uni.$emit("socket_error", e);
  87. },
  88. close: function() {
  89. uni.closeSocket();
  90. }
  91. };
  92. Socket.prototype.constructor = Socket;
  93. export default Socket;