后端
新建Webapi項目
創建 ChatHub
類,繼承於 Hub
public class ChatHub : Hub { public async Task SendMessage(string user,string message) { await Clients.All.SendAsync("ReceiveMessage", user, message); } }
啟用ChatHub,將ChartHub映射到路徑 /chathub
下(需要前后端約定)
app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapHub<ChatHub>("/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,設置路由,具體代碼如下
<template>
<div class="hello">
<!-- <img alt="Vue logo" src="../assets/logo.png"> -->
<el-input type="textarea" :rows="10" v-model="textarea1" style="width:45%">
</el-input>
<div>
<el-input v-model="name" placeholder="姓名" style="width:200px"></el-input>
<el-input v-model="message" placeholder="信息" style="width:200px"></el-input>
<el-button type="primary" @click="send">發送</el-button>
</div>
</div>
</template>
<script lang="ts"> import { Component, Prop, Vue } from 'vue-property-decorator'; import * as signalR from '@microsoft/signalr'; @Component export default class Chat extends Vue { @Prop() private msg!: string; // var divMessage: HTMLDivElement = document.querySelector(".hello");
private textarea1 = '1231'; private name= ''; private message= ''; private hubConnection: signalR.HubConnection = new signalR.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); } } </script>
前端顯示如下
import * as signalR from '@microsoft/signalr';
將SignalR引入到當前頁,定義hubConnection繼承於signalR.HubConnection。
通過withUrl("https://localhost:44342/chatHub")將前端跟后端提供的接口綁定(后端啟動端口是44342)。
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); }
具體效果如下