SignalR是一個.NET庫,用于在客戶端和服務器之間實時通信。Blazor WebAssembly是一個使用WebAssembly技術在瀏覽器中運行.NET代碼的框架。要在Blazor WebAssembly應用中集成SignalR,可以按照以下步驟操作:
dotnet add package Microsoft.AspNetCore.SignalR.Client
using Microsoft.AspNetCore.SignalR.Client;
public class SignalRService
{
private HubConnection hubConnection;
public SignalRService()
{
hubConnection = new HubConnectionBuilder()
.WithUrl("https://<your-signalr-server-url>")
.Build();
}
public async Task StartConnection()
{
await hubConnection.StartAsync();
}
public HubConnection GetHubConnection()
{
return hubConnection;
}
}
@page "/signalr"
@inject SignalRService signalRService
@code {
protected override async Task OnInitializedAsync()
{
await signalRService.StartConnection();
signalRService.GetHubConnection().On<string>("ReceiveMessage", (message) =>
{
// 處理接收到的消息
});
}
}
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", $"{user}: {message}");
}
}
@page "/signalr"
<input @bind="user" placeholder="Enter your name" />
<input @bind="message" placeholder="Enter your message" />
<button @onclick="SendMessage">Send</button>
@code {
private string user;
private string message;
private async Task SendMessage()
{
await signalRService.GetHubConnection().InvokeAsync("SendMessage", user, message);
}
}
通過以上步驟,您可以在Blazor WebAssembly應用中集成SignalR,并實現實時通信功能。您可以根據自己的需求修改以上代碼來實現不同的功能。