ASP.NET SignalR 是一个用于构建实时 Web 应用程序的库,它允许服务器与客户端之间进行双向通信。要实现 SignalR 与其他系统的对接,你需要遵循以下步骤:
Install-Package Microsoft.AspNetCore.SignalR
Hub
:public class MyHub : Hub { public async Task SendMessage(string user, string message) { await Clients.All.SendAsync("ReceiveMessage", user, message); } }
Startup.cs
文件中,配置 SignalR 以使用 Hub 路由。将以下代码添加到 ConfigureServices
方法中:services.AddSignalR();
然后,在 Configure
方法中添加以下代码:
app.UseEndpoints(endpoints => { endpoints.MapHub<MyHub>("/myhub"); });
<!DOCTYPE html> <html> <head> <title>SignalR Example</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/aspnet-signalr/5.0.7/signalr.min.js"></script> </head> <body> <input type="text" id="userInput" placeholder="Enter your name"> <input type="text" id="messageInput" placeholder="Enter your message"> <button id="sendButton">Send</button> <ul id="messages"></ul> <script> $(document).ready(function () { const connection = new signalR.HubConnectionBuilder().withUrl("/myhub").build(); connection.on("ReceiveMessage", function (user, message) { $("#messages").append($("<li>").text(`${user}: ${message}`)); }); $("#sendButton").click(function () { const user = $("#userInput").val(); const message = $("#messageInput").val(); connection.invoke("SendMessage", user, message); }); connection.start().catch(function (error) { console.error("Error connecting to SignalR Hub:", error); }); }); </script> </body> </html>
总之,要实现对其他系统的对接,你需要根据目标系统的通信协议来调整客户端和服务器端的代码,并在必要时编写额外的逻辑来处理与其他系统的交互。