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>
以上就是c#使用signalr实现与前端vue实时通信的示例代码的详细内容,更多关于c# signalr与vue通信的资料请关注代码网其它相关文章!
发表评论