chat.js 1.3 KB

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