本文主要是介绍signalR+websocket:实现消息实时通讯——技能提升,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
signalR
解决步骤1:npm install @microsoft/signalr@6.0.6
安装指定版本的@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);
},
这篇关于signalR+websocket:实现消息实时通讯——技能提升的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!