new_chat.js 2.3 KB

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