最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#使用SignalR實現(xiàn)與前端vue實時通信的示例代碼

 更新時間:2024年10月14日 10:02:57   作者:敲厲害的燕寶  
SignalR 是 ASP.NET Core 的一個庫,它簡化了在應用程序中添加實時通信的過程,無論是聊天應用、實時游戲還是協(xié)作工具,SignalR 都能提供高效且易于實現(xiàn)的解決方案,本文給大家介紹了C#使用SignalR實現(xiàn)與前端vue實時通信的實現(xiàn),需要的朋友可以參考下

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、創(chuàng)建Hub類

創(chuàng)建一個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>
 ///  分組發(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 項目中安裝了必要的依賴:

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');
 
// 創(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));

頁面引用

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();
 
          // 處理連接狀態(tài)變化
          this.connection.onclose(async () => {
            await this.start();
          });
 
          // 監(jiān)聽服務器發(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實現(xiàn)與前端vue實時通信的示例代碼的詳細內(nèi)容,更多關于C# SignalR與Vue通信的資料請關注腳本之家其它相關文章!

相關文章

最新評論

保定市| 平乡县| 禹州市| 安国市| 厦门市| 渝北区| 林甸县| 岱山县| 福清市| 绍兴县| 抚远县| 建湖县| 寿阳县| 通化县| 介休市| 祥云县| 电白县| 抚州市| 垦利县| 新民市| 西和县| 高要市| 交口县| 营山县| 乐平市| 永昌县| 淮滨县| 密云县| 衡东县| 博白县| 新巴尔虎右旗| 璧山县| 当涂县| 鹤庆县| 金堂县| 安溪县| 五大连池市| 淮北市| 大邑县| 沙湾县| 泰顺县|