WebsocketMixin.js 2.1 KB

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