vue+element +signalR 即时消息
如果要使用signalR 先要安装,网上很多可以查看命令,引入项目
这里的代码是前端代码
// 1 创建
this.connection = new signalR.HubConnectionBuilder()
.withAutomaticReconnect()//断线自动重连 它会默认连接4次
.withUrl(URL, {//连接地址
skipNegotiation: true,//跳过协商步骤
transport: signalR.HttpTransportType.WebSockets,//指定连接方式
})
.configureLogging(signalR.LogLevel.Information)
.build();
// 自动重连成功后的处理
this.connection.onreconnected((connectionId) => {
//如果没有设置跳过协商步骤 connectionId 会更新
this.$message.success('服务器重新连接成功。');
})
//2 注册
//注册方法 前端定义的方法 供服务端调用
this.connection.on("ReceiveMessage", this.Sendasync);
//3 开始连接
this.connection
.start()
.then((res) => {
})
.catch((err) => {
this.$message.error('连接失败。');
});
//关闭连接 如果客户端在其前四次尝试中成功重新连接,则 HubConnection 将转换回 Connected 状态并触发其 onreconnected 回调。 这样就可通知用户已重新建立连接。
this.connection.onclose(error => {})
//4 发布消息 invoke 调用后端定义的方法 SendMessage服务端方法
this.connection
.invoke("SendMessage", 传入的参数)
.then(() => {
//发布成功处理逻辑
})
.catch((err) => {
//发布失败处理逻辑
})
如果有不清除的可以查看官方文档
signalR