chat.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import $store from "@/store";
  2. import { VUE_APP_WS_URL } from "@utils";
  3. const Socket = function() {
  4. this.ws = new WebSocket(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. Socket.prototype = {
  11. vm(vm) {
  12. this.vm = vm;
  13. },
  14. close() {
  15. clearInterval(this.timer);
  16. this.ws.close();
  17. },
  18. onOpen: function() {
  19. console.log("ws open");
  20. this.init();
  21. this.send({
  22. type: "login",
  23. data: $store.state.app.token
  24. });
  25. this.vm.$emit("socket_open");
  26. },
  27. init: function() {
  28. var that = this;
  29. this.timer = setInterval(function() {
  30. that.send({ type: "ping" });
  31. }, 10000);
  32. },
  33. send: function(data) {
  34. return this.ws.send(JSON.stringify(data));
  35. },
  36. onMessage: function(res) {
  37. const { type, data = {} } = JSON.parse(res.data);
  38. this.vm.$emit(type, data);
  39. },
  40. onClose: function() {
  41. clearInterval(this.timer);
  42. },
  43. onError: function(e) {
  44. console.log(e);
  45. this.vm.$emit("socket_error", e);
  46. }
  47. };
  48. Socket.prototype.constructor = Socket;
  49. export default Socket;