a565e94d6388b8d4f790dbcc91108a7991e86fef.svn-base 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import store from '@/store/'
  2. import { ACCESS_TOKEN } from '@/store/mutation-types'
  3. import Vue from 'vue'
  4. export const WebsocketMixin = {
  5. mounted() {
  6. this.initWebSocket();
  7. },
  8. destroyed: function () {
  9. // 离开页面生命周期函数
  10. this.websocketOnclose();
  11. },
  12. methods:{
  13. initWebSocket: function () {
  14. let token = Vue.ls.get(ACCESS_TOKEN)
  15. console.log("------------WebSocket连接成功");
  16. // WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于https
  17. var userId = store.getters.userInfo.id;
  18. if(!this.socketUrl.startsWith('/')){
  19. this.socketUrl = '/' + this.socketUrl
  20. }
  21. if(!this.socketUrl.endsWith('/')){
  22. this.socketUrl = this.socketUrl + '/'
  23. }
  24. var url = window._CONFIG['domianURL'].replace("https://","wss://").replace("http://","ws://") + this.socketUrl + userId + "/" + token;
  25. this.websock = new WebSocket(url);
  26. this.websock.onopen = this.websocketOnopen;
  27. this.websock.onerror = this.websocketOnerror;
  28. this.websock.onmessage = this.websocketOnmessage;
  29. this.websock.onclose = this.websocketOnclose;
  30. },
  31. websocketOnopen: function () {
  32. console.log("WebSocket连接成功");
  33. },
  34. websocketOnerror: function (e) {
  35. console.log("WebSocket连接发生错误");
  36. this.reconnect();
  37. },
  38. websocketOnclose: function (e) {
  39. this.reconnect();
  40. },
  41. websocketSend(text) {
  42. // 数据发送
  43. try {
  44. this.websock.send(text);
  45. } catch (err) {
  46. console.log("send failed (" + err.code + ")");
  47. }
  48. },
  49. reconnect() {
  50. var that = this;
  51. if(that.lockReconnect) return;
  52. that.lockReconnect = true;
  53. //没连接上会一直重连,设置延迟避免请求过多
  54. setTimeout(function () {
  55. console.info("尝试重连...");
  56. that.initWebSocket();
  57. that.lockReconnect = false;
  58. }, 5000);
  59. },
  60. }
  61. }