您可以使用SignalR 之类的 websocket 技术。它有三种风格:ASP.NET SignalR、ASP.NET Core SignalR 和 Azure SignalR(SignalR 以 Azure 作为主干)。比较每个版本here 和here。
您应该从 IHubContext 获取上下文并将其连接起来,如您所见 here:
public class HomeController : Controller
{
private readonly IHubContext<NotificationHub> _hubContext;
public HomeController(IHubContext<NotificationHub> hubContext)
{
_hubContext = hubContext;
}
}
根据文档,IHubContext 可能在以下情况下使用:
IHubContext 用于向客户端发送通知,不用于调用 Hub 上的方法。
现在,要连接客户端,您可以选择正确的技术(javascript、typescript 等)。可以在此处找到示例(来自 microsoft docs):
"use strict";
var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;
connection.on("ReceiveMessage", function (user, message) {
var li = document.createElement("li");
document.getElementById("messagesList").appendChild(li);
// We can assign user-supplied strings to an element's textContent because it
// is not interpreted as markup. If you're assigning in any other way, you
// should be aware of possible script injection concerns.
li.textContent = `${user} says ${message}`;
});
connection.start().then(function () {
document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
return console.error(err.toString());
});
document.getElementById("sendButton").addEventListener("click", function (event) {
var user = document.getElementById("userInput").value;
var message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
还可以提到Socket.IO,我个人以前从未使用过。
愉快的编码