C#后端
1、安装SignalR包
首先确保项目中已安装 SignalR 相关包。可以通过 NuGet 包管理器安装:
dotnet add package Microsoft.AspNetCore.SignalR
2、配置SignalR
在 Startup.cs 文件中配置 SignalR
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chatHub");
});
}
}
3、创建Hub类
创建一个msgHub类来处理客户端的连接和消息传递
using Microsoft.AspNetCore.SignalR;
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
/// <summary>
/// 将客户端加入指定分组
/// </summary>
/// <param name="groupName"></param>
/// <returns></returns>
public async Task JoinGroup(string groupName)
{
// 将客户端加入指定分组
await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
}
/// <summary>
/// 将客户端从指定分组移出
/// </summary>
/// <param name="groupName"></param>
/// <returns></returns>
public async Task LeaveGroup(string groupName)
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);
}
/// <summary>
/// 分组发送消息
/// </summary>
/// <param name="user"></param>
/// <param name="message"></param>
/// <returns></returns>
public async Task SendMessageToOneGroup( string user, object message)
{
await Clients.Group("One").SendAsync(HubsConstant.DisplayReceive, user, message);
}
}
客户端Vue连接
1、安装依赖
确保你的 Vue.js 项目中安装了必要的依赖:
Vue.js:确保你有一个 Vue.js 项目。
SignalR 客户端库:安装 SignalR 客户端库。
可以通过 npm 安装 SignalR 客户端库:
npm install @microsoft/signalr
2、修改 src/main.js 文件
确保在 Vue.js 应用中全局引入 SignalR:
全局引用
import Vue from 'vue';
import App from './App.vue';
import { HubConnectionBuilder } from '@microsoft/signalr';
Vue.config.productionTip = false;
new Vue({
render: h => h(App),
}).$mount('#app');
// 创建 SignalR 连接
let connection = new HubConnectionBuilder()
.withUrl('http://localhost:5000/chatHub')
.build();
connection.on('ReceiveMessage', (user, message) => {
console.log(`${user}: ${message}`);
// 更新 UI
});
connection.start().catch(err => console.error(err));
页面引用
import { HubConnectionBuilder } from '@microsoft/signalr';
3、页面index.vue使用
<template>
</template>
<script>
import { HubConnectionBuilder } from '@microsoft/signalr';
export default {
name: "WebSocketTest",
mounted() {
this.start();
},
beforeDestroy() {
this.leaveGroup();
},
methods: {
async start() {
try {
this.connection = new HubConnectionBuilder()
.withUrl('http://localhost:8888/msgHub')
.configureLogging(1)
.build();
// 处理连接状态变化
this.connection.onclose(async () => {
await this.start();
});
// 监听服务器发送的消息
this.connection.on('DisplayReceive', (user, message) => {
console.log('Received message:', user, message);
await this.connection.start();
console.log('Connection started');
// 加入分组
await this.connection.invoke('JoinGroup', 'One').catch(err => console.error('Error joining group:', err));
} catch (err) {
console.error('Error while starting connection:', err);
setTimeout(() => this.start1(), 5000);
}
},
async leaveGroup() {
//移出分组
await this.connection.invoke('LeaveGroup', 'One').catch(err => console.error('Error leaving group:', err));
await this.connection.stop();
},
}
}
</script>
标签:vue,err,C#,await,SignalR,connection,message,public
From: https://blog.csdn.net/m0_63456808/article/details/142894580