chat.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import $store from "@/store";
  2. import { VUE_APP_WS_URL } from "@/utils/index.js";
  3. import { mapState } from 'vuex';
  4. const Socket = function() {
  5. this.ws = new WebSocket(wss(VUE_APP_WS_URL));
  6. this.ws.onopen = this.onOpen.bind(this);
  7. this.ws.onerror = this.onError.bind(this);
  8. this.ws.onmessage = this.onMessage.bind(this);
  9. this.ws.onclose = this.onClose.bind(this);
  10. };
  11. function wss(wsSocketUrl) {
  12. let ishttps = document.location.protocol == 'https:';
  13. if (ishttps) {
  14. return wsSocketUrl.replace('ws:', 'wss:');
  15. } else {
  16. return wsSocketUrl.replace('wss:', 'ws:');
  17. }
  18. }
  19. let token = uni.getStorageSync('token');
  20. Socket.prototype = {
  21. vm(vm) {
  22. this.vm = vm;
  23. },
  24. close() {
  25. clearInterval(this.timer);
  26. this.ws.close();
  27. },
  28. onOpen: function() {
  29. console.log("ws open");
  30. this.init();
  31. this.send({
  32. type: "login",
  33. data: token
  34. });
  35. this.vm.$emit("socket_open");
  36. },
  37. init: function() {
  38. var that = this;
  39. this.timer = setInterval(function() {
  40. that.send({ type: "ping" });
  41. }, 10000);
  42. },
  43. send: function(data) {
  44. return this.ws.send(JSON.stringify(data));
  45. },
  46. onMessage: function(res) {
  47. const { type, data = {} } = JSON.parse(res.data);
  48. this.vm.$emit(type, data);
  49. },
  50. onClose: function() {
  51. clearInterval(this.timer);
  52. },
  53. onError: function(e) {
  54. console.log(e);
  55. this.vm.$emit("socket_error", e);
  56. }
  57. };
  58. Socket.prototype.constructor = Socket;
  59. export default Socket;