chat.js 1.4 KB

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