weixin_58412143 2022-03-02 16:28 采纳率: 93.8%
浏览 71
已结题

vue 轴实现SockJS +websocket请求

1Vue里引入  import websocket from '../../utils/websocket.js';**PS:但是好像没有引入进来不知道为什么,确定路径没有写错**
2// 安装并引入相关模块——此部分写在了websocket.js里
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
export default {
 data() {
  return {
  dataList: []
  };
 },
 mounted:function(){
   console.log("09999")
  this.initWebSocket();
 },
 beforeDestroy: function () {
  // 页面离开时断开连接,清除定时器
  this.disconnect();
  clearInterval(this.timer);
 },
 methods: {
  initWebSocket() {
  this.connection();
  let self = this;
  // 断开重连机制,尝试发送消息,捕获异常发生时重连
  this.timer = setInterval(() => {
   try {
   self.stompClient.send("test");
   } catch (err) {
   console.log("断线了: " + err);
   self.connection();
   }
  }, 5000);
  },
  removeTab(targetName) {
  console.log(targetName)
  },
  connection() {
  // 建立连接对象
  this.socket = new SockJS('ws://47.94.52.215:8001/WS/');//连接服务端提供的通信接口
  // 获取STOMP子协议的客户端对象
  this.stompClient = Stomp.over(this.socket);
  // 定义客户端的认证信息,按需求配置
  var headers = {
   login: 'mylogin',
   passcode: 'mypasscode',
   // additional header
   'client-id': 'my-client-id'
  };
  // 向服务器发起websocket连接
  this.stompClient.connect(headers,(frame) => {
    console.log("发起websocket连接成功");
    // this.stompClient.subscribe('/pc', (res) => { // 订阅服务端提供的某个topic
    // consolel.log(res.body); // msg.body存放的是服务端发送给我们的信息
    // });
     this.stompClient.subscribe('/topic/chat_msg', (msg) => { // 订阅服务端提供的某个topic
     consolel.log(msg.body); // msg.body存放的是服务端发送给我们的信息
     });
  }, (err) => {
    console.log("发起websocket连接失败");
  });

  },
  disconnect() {
  if (this.stompClient != null) {
   this.stompClient.disconnect();
   console.log("Disconnected");
  }
  }
 }
};

  • 写回答

1条回答 默认 最新

  • weixin_58412143 2022-03-09 15:34
    关注

    1

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

    报告相同问题?

    问题事件

    • 系统已结题 3月17日
    • 已采纳回答 3月9日
    • 创建了问题 3月2日

    悬赏问题

    • ¥15 eclipse无法正常运行
    • ¥15 定义了函数,但是无法根据函数定义触发器
    • ¥20 5变量卡诺图化简得出与非门电路图
    • ¥15 Python爬取交通拥堵指数数据
    • ¥15 使用vba抓取重定向网页问题
    • ¥20 付费需求测试程序(细谈)。
    • ¥15 为什么这段c++代码会报这么多语法错误?
    • ¥50 vue-codemirror如何对指定行 指定位置的 字符进行背景颜色或者字体颜色的修改?
    • ¥30 遇到一个的问题,请教各位
    • ¥20 matlab报错,vflux计算潜流通量