new_chat.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import $store from "@/store";
  2. import {
  3. HTTP_REQUEST_URL
  4. } from "@/config/app.js";
  5. import {
  6. VUE_APP_WS_URL
  7. } from "@/utils/index.js";
  8. import {
  9. getServerType
  10. } from '@/api/api.js';
  11. const Socket = function() {
  12. // this.ws.close(this.close.bind(this));
  13. };
  14. // #ifdef H5
  15. function wss(wsSocketUrl) {
  16. let ishttps = document.location.protocol == 'https:';
  17. if (ishttps) {
  18. return wsSocketUrl.replace('ws:', 'wss:');
  19. } else {
  20. return wsSocketUrl.replace('wss:', 'ws:');
  21. }
  22. }
  23. // #endif
  24. Socket.prototype = {
  25. // close() {
  26. // clearInterval(this.timer);
  27. // this.ws.close();
  28. // },
  29. onSocketOpen: function(my) {
  30. uni.$emit('socketOpen', my)
  31. },
  32. init: function() {
  33. var that = this;
  34. this.timer = setInterval(function() {
  35. that.send({
  36. type: "ping"
  37. });
  38. }, 10000);
  39. },
  40. send: function(data) {
  41. let datas = JSON.stringify(data)
  42. return uni.sendSocketMessage({
  43. data: datas
  44. });
  45. },
  46. onMessage: function(res) {
  47. const {
  48. type,
  49. data = {}
  50. } = JSON.parse(res.data);
  51. uni.$emit(type, data)
  52. },
  53. onClose: function() {
  54. uni.closeSocket()
  55. clearInterval(this.timer);
  56. uni.$emit("socket_close");
  57. },
  58. onError: function(e) {
  59. uni.$emit("socket_error", e);
  60. },
  61. close: function() {
  62. uni.closeSocket();
  63. },
  64. onStart: function(token, form_type) {
  65. let wssUrl = `${VUE_APP_WS_URL}`
  66. this.ws = uni.connectSocket({
  67. url: wssUrl + '?type=user&token=' + token + '&form_type=' + form_type,
  68. header: {
  69. 'content-type': 'application/json'
  70. },
  71. method: 'GET',
  72. success: (res) => {}
  73. });
  74. this.ws.onOpen(this.onSocketOpen.bind(this))
  75. this.ws.onError(this.onError.bind(this));
  76. this.ws.onMessage(this.onMessage.bind(this))
  77. this.ws.onClose(this.onClose.bind(this));
  78. }
  79. };
  80. Socket.prototype.constructor = Socket;
  81. export default Socket;