php前后端分离实现消息推送,前后端分离下使用SignalR

论坛 期权论坛 脚本     
已经匿名di用户   2021-11-19 14:38   3173   0

后端

新建Webapi项目

创建 ChatHub 类,继承于 Hub

public classChatHub : Hub

{public async Task SendMessage(string user,stringmessage)

{await Clients.All.SendAsync("ReceiveMessage", user, message);

}

}

启用ChatHub,将ChartHub映射到路径 /chathub 下(需要前后端约定)

app.UseEndpoints(endpoints =>{

endpoints.MapControllers();

endpoints.MapHub("/chathub");

});

后端启用CORS

8080是前端的端口,前后端分离需要设置跨域,否则无法正常访问

//ConfigureServices

services.AddSignalR();//Configure

app.UseCors(builder =>{

builder.WithOrigins("http://localhost:8080")

.AllowAnyMethod()

.AllowCredentials()

.AllowAnyHeader();

});

通过刚才的代码,我们将 ChatHub 下的方法映射到路径 /chathub 下

前端

前端引入 @microsoft/signalr,使用 npm install进行安装

"dependencies": {"@microsoft/signalr": "3.1.2","core-js": "^3.6.4","element-ui": "^2.13.0","vue": "^2.6.11","vue-class-component": "^7.2.2","vue-property-decorator": "^8.3.0","vue-router": "^3.1.5","vuex": "^3.1.2"},

具体Element-ui以及路由不再赘述,可以看之前的文章。

新建Chat.vue,设置路由,具体代码如下

发送

import* as signalR from ‘@microsoft/signalr‘;

@Component

exportdefault classChat extends Vue {

@Prop()private msg!: string;//var divMessage: HTMLDivElement = document.querySelector(".hello");

private textarea1 = ‘1231‘;private name= ‘‘;private message= ‘‘;private hubConnection: signalR.HubConnection = newsignalR.HubConnectionBuilder()

.withUrl("https://localhost:44342/chatHub")

.withAutomaticReconnect()//.configureLogging(signalR.LogLevel.Information)

.build();

mounted() {this.start();this.hubConnection.on("ReceiveMessage",(name,message)=>{this.textarea1 = this.textarea1.concat( ‘\r\n‘ + name + ‘:‘

+message);

});

}

start():void{this.hubConnection.start()

.then(a=>{if(this.hubConnection.connectionId){ //this.hubConnection.invoke("SendMessage",this.name,this.message).catch(err=>console.log(err.toString()));

}

});

}

send(){this.hubConnection.send("SendMessage",this.name,this.message);

}

}

前端显示如下

59a68cdb128eba796f87f55a4478c4b7.png

import * as signalR from [email protected]/signalr‘;

将SignalR引入到当前页,定义hubConnection继承于signalR.HubConnection。

this.hubConnection.on("ReceiveMessage",(name,message)=>{this.textarea1 = this.textarea1.concat( ‘\r\n‘ + name + ‘:‘

+ message);

前端监听 ReceiveMessage 方法,该方法需要和后端提供一样的签名,作用是将接收到的name和message属性打印到页面上。

定义Send方法,将在点击按钮的时候出发Click事件,将信息发送

send(){this.hubConnection.send("SendMessage",this.name,this.message);

}

具体效果如下

c926ce988db73d8b6c1bbe89cd20cf66.gif

参考

原文:https://www.cnblogs.com/imstrive/p/12502939.html

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:81
帖子:4969
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP