在ASP.NET Core中使用SignalR實現實時通信的步驟如下:
Install-Package Microsoft.AspNetCore.SignalR
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
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");
});
}
<script src="https://cdn.jsdelivr.net/npm/@microsoft/signalr@latest/dist/browser/signalr.min.js"></script>
<script>
var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
connection.on("ReceiveMessage", function (user, message) {
// 處理接收到的消息
});
connection.start().then(function () {
// 連接成功后的操作
}).catch(function (err) {
console.error(err.toString());
});
</script>
通過以上步驟,您可以在ASP.NET Core中使用SignalR實現實時通信。在客戶端調用SendMessage
方法向服務器發送消息,并在接收到消息時使用ReceiveMessage
事件處理程序處理實時消息。