chat.js 1.8 KB

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