C#使用SignalR實(shí)現(xiàn)與前端vue實(shí)時(shí)通信的示例代碼
C#后端
1、安裝SignalR包
首先確保項(xiàng)目中已安裝 SignalR 相關(guān)包??梢酝ㄟ^(guò) 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、創(chuàng)建Hub類
創(chuàng)建一個(gè)msgHub類來(lái)處理客戶端的連接和消息傳遞
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> /// 分組發(fā)送消息 /// </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 項(xiàng)目中安裝了必要的依賴:
Vue.js:確保你有一個(gè) Vue.js 項(xiàng)目。
SignalR 客戶端庫(kù):安裝 SignalR 客戶端庫(kù)。
可以通過(guò) npm 安裝 SignalR 客戶端庫(kù):
npm install @microsoft/signalr
2、修改 src/main.js 文件
確保在 Vue.js 應(yīng)用中全局引入 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'); // 創(chuàng)建 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));
頁(yè)面引用
import { HubConnectionBuilder } from '@microsoft/signalr';
3、頁(yè)面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(); // 處理連接狀態(tài)變化 this.connection.onclose(async () => { await this.start(); }); // 監(jiān)聽(tīng)服務(wù)器發(fā)送的消息 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實(shí)現(xiàn)與前端vue實(shí)時(shí)通信的示例代碼的詳細(xì)內(nèi)容,更多關(guān)于C# SignalR與Vue通信的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#?wpf?Bitmap轉(zhuǎn)換成WriteableBitmap的方法
本文主要介紹了C#?wpf?Bitmap轉(zhuǎn)換成WriteableBitmap的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08C#代碼實(shí)現(xiàn)短信驗(yàn)證碼接口示例
這篇文章主要為大家詳細(xì)介紹了C#實(shí)現(xiàn)短信驗(yàn)證碼接口示例代碼,感興趣的小伙伴們可以參考一下2016-08-08C#前端驗(yàn)證和后臺(tái)驗(yàn)證代碼實(shí)例
這篇文章主要介紹了C#前端驗(yàn)證和后臺(tái)驗(yàn)證代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07WinForm實(shí)現(xiàn)自定義右下角提示效果的方法
這篇文章主要介紹了WinForm實(shí)現(xiàn)自定義右下角提示效果的方法,涉及WinForm自定義提示效果的實(shí)現(xiàn)方法,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-08-08