SoketJs连接socket服务,订阅topic

该博客展示了一段JavaScript代码,用于实现WebSocket连接。代码包含初始化WebSocket、建立连接、断开连接、显示响应和发送消息等功能,还设置了断开重连机制,通过定时发送消息捕获异常来触发重连,同时订阅服务端的topic接收响应。

var socket = {
  initWebSocket() {
      this.connection();
      let that= this;
      // 断开重连机制,尝试发送消息,捕获异常发生时重连
      this.timer = setInterval(() => {
        try {
          that.stompClient.send("test");
        } catch (err) {
          console.log("断线了: " + err);
          that.connection();
        }
      }, 5000);
      this.sendName();
    },

    connection() {
      let headers = {
        token:store.getters.token,
        username:  window.localStorage.getItem('faceUserName')
      };

      // 建立连接对象
      let socket = new SockJS('http://localhost:8080/bullet?token=' + headers.token + '&username=' + headers.username);
      // 获取STOMP子协议的客户端对象
      this.stompClient = Stomp.over(socket);

      // 向服务器发起websocket连接
      this.stompClient.connect(headers,() => {
        this.stompClient.subscribe('/topic/getResponse', (response) => { // 订阅服务端提供的某个topic
          console.log("topic/getResponse", response)
          this.showResponse(response);
        });
      }, (err) => {
        // 连接发生错误时的处理函数
        // console.log('失败')
        console.log("订阅失败",err);
      });
    },   

    disconnect() {
      if (this.stompClient) {
        this.stompClient.disconnect();
      }
    }, 

    showResponse(message){
      console.log(message);
    },
    
    sendName() {
      let that = this;
      setInterval(function () {
        try{
          that.stompClient.send("/app/chat", {}, JSON.stringify({'username': "tom", 'message':'hello xiaoming'}));//5
        }catch (e) {
          console.log(e)
        }
      }, 5000)

    }
}

 

转载于:https://my.oschina.net/moyesen/blog/3071843

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值