signalR+websocket:实现消息实时通讯——技能提升

signalR

解决步骤1:npm install @microsoft/[email protected]

安装指定版本的@microsoft/signalr,我这边安装的版本是6.0.6

解决步骤2:引入import * as signalR from '@microsoft/signalr';

import * as signalR from '@microsoft/signalr';
下面第三步会用到token,所以此处也先引用一下cookie
import Cookie from 'js-cookie';

解决步骤3:使用方法

let hubUrl = process.env.VUE_APP_API_BASE_URL + '/my_hub';
var token = Cookie.get('Authorization');
token = token.replace('Bearer', '').trim();
this.connection = new signalR.HubConnectionBuilder()
  .withUrl(hubUrl, { accessTokenFactory: () => token })
  .withAutomaticReconnect()
  .build();
this.connection
  .start()
  .then(() => {
    // 连接成功后,订阅消息
    console.log('连接成功后,订阅消息');
  })
  .catch((err) => {
    // 连接异常时的处理
    console.log('连接异常时的处理');
  });
//自动重连成功后的处理
this.connection.onreconnected((connectionId) => {
  console.log(connectionId);
});
this.connection.on('ReceiveMessage', (message) => {
  console.log(message.split('::')[0]);
  this.$notification.info({
    message: message.split('::')[0],
    description: message.split('::')[1],
    onClick: () => {
      console.log('Notification Clicked!');
    },
    duration: 4.5,
  });
});

websocket

解决步骤1:定义参数

data(){
	return{
	  websocket: null,
      setIntervalWesocketPush: null,
      againSocket: true,
	}
}

解决步骤2:初始化websocket

initWebSocket() {
  let that = this;
  var websocket = null;
  if ('WebSocket' in window) {
    websocket = new WebSocket('wss://echo.websocket.org/');
  } else {
    alert('该浏览器不支持websocket!');
  }
  websocket.onopen = function (event) {
    console.log('建立连接');
    websocket.send('Hello WebSockets!');
  };
  websocket.onclose = function (event) {
    console.log('连接关闭');
    that.reconnect(); //尝试重连websocket
  };
  //建立通信后,监听到后端的数据传递
  websocket.onmessage = function (event) {
    console.log(event);
  };
  websocket.onerror = function () {
    // notify.warn("websocket通信发生错误!");
    // initWebSocket()
  };
  window.onbeforeunload = function () {
    websocket.close();
  };
},

解决步骤3:断连后的重连

// 重连
reconnect() {
  console.log('正在重连');
  // 进行重连
  setTimeout(() => {
    this.initWebSocket();
  }, 1000);
},

你可能感兴趣的:(javascript知识点,js必会知识点,vue技能提升,websocket,网络协议,网络)