亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

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的方法

    本文主要介紹了C#?wpf?Bitmap轉(zhuǎn)換成WriteableBitmap的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-08-08
  • 如何在C#中使用OpenCV(GOCW使用教程)

    如何在C#中使用OpenCV(GOCW使用教程)

    這篇文章主要介紹了如何在C#中使用OpenCV(GOCW使用教程),幫助大家更好的理解和使用c#,感興趣的朋友可以了解下
    2020-12-12
  • 基于C#實(shí)現(xiàn)的敏感字檢測(cè)示例

    基于C#實(shí)現(xiàn)的敏感字檢測(cè)示例

    這篇文章主要介紹了基于C#實(shí)現(xiàn)的敏感字檢測(cè)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-09-09
  • C#代碼實(shí)現(xiàn)短信驗(yàn)證碼接口示例

    C#代碼實(shí)現(xiàn)短信驗(yàn)證碼接口示例

    這篇文章主要為大家詳細(xì)介紹了C#實(shí)現(xiàn)短信驗(yàn)證碼接口示例代碼,感興趣的小伙伴們可以參考一下
    2016-08-08
  • C# DialogResult用法案例詳解

    C# DialogResult用法案例詳解

    這篇文章主要介紹了C# DialogResult用法案例詳解,本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • C#前端驗(yàn)證和后臺(tái)驗(yàn)證代碼實(shí)例

    C#前端驗(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-07
  • 游戲開(kāi)發(fā)之隨機(jī)概率的選擇算法

    游戲開(kāi)發(fā)之隨機(jī)概率的選擇算法

    這篇文章主要介紹了游戲開(kāi)發(fā)之隨機(jī)概率的選擇算法,需要的朋友可以參考下
    2015-07-07
  • WinForm實(shí)現(xiàn)自定義右下角提示效果的方法

    WinForm實(shí)現(xiàn)自定義右下角提示效果的方法

    這篇文章主要介紹了WinForm實(shí)現(xiàn)自定義右下角提示效果的方法,涉及WinForm自定義提示效果的實(shí)現(xiàn)方法,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-08-08
  • 判斷圖片-判斷位圖是否是黑白圖片的方法

    判斷圖片-判斷位圖是否是黑白圖片的方法

    近來(lái)工作需要判斷圖片否是是彩色的,由于是十萬(wàn)張以上的大批量理處,所以通過(guò)序程來(lái)動(dòng)自判斷。
    2013-05-05
  • C#并發(fā)編程之Task類詳解

    C#并發(fā)編程之Task類詳解

    Task是建立在線程池之上的一種多線程技術(shù),它的出現(xiàn)使Thread成為歷史。其使用方法非常簡(jiǎn)單,本文就來(lái)通過(guò)幾個(gè)示例為大家講講它的具體使用吧
    2023-03-03

最新評(píng)論