SignalR 未接收消息 aspNet



我正在尝试接收两个不同的相同网页之间的消息,以便两个网页上的asp:label可以提供有关每个下拉列表中当前选择的内容的信息。

网页代码

protected void Page_Load(object sender, EventArgs e)
{
IHubProxy _hub;
string url = @"http://localhost:8080/";
var connection = new HubConnection(url);
_hub = connection.CreateHubProxy("Hub");
connection.Start().Wait();
_hub.On("ReceiveMessage", x => CurrentInfo.Text = x);
}
protected void SaveStates_Click(object sender, EventArgs e)
{
//Set the hubs URL for the connection
string url = "http://localhost:8080/signalr";
// Declare a proxy to reference the hub.
var connection = new HubConnection(url);
var _hub = connection.CreateHubProxy("Hub");
connection.Start().Wait();
_hub.Invoke("SendMessage", "Hello").Wait();
}

中心代码

static void Main(string[] args)
{
string url = @"http://localhost:8080/";
using (WebApp.Start<Startup>(url))
{
Console.WriteLine(string.Format("Server running at {0}", url));
Console.ReadLine();
}
}
[HubName("Hub")]
public class SignalHub : Hub
{
public void SendMessage(string message)
{
Console.WriteLine(message);
Clients.All.ReceiveMessage(message);
//TODO:
//Respond to Messages
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}

目前发生了什么?

目前,asp:label 仅更新发送消息的特定页面。对于两者,我在上面的代码中做错了什么。

任何帮助将不胜感激。提前致谢

编辑

如果有人能为它在 JS 中工作提供一些演示代码,我将不胜感激。我找到的所有示例都不起作用

你应该像这样创建你的客户端:

引用信号器.js和聊天.js在 HTML 页面中,您可以使用信号器。

<script src="~/lib/signalr/signalr.js"></script>
<script src="~/js/chat.js"></script>

聊天内容.js:

"use strict";
var connection = new signalR.HubConnectionBuilder().withUrl("/hub").build();
connection.on("ReceiveMessage", function (user, message) {
var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
var encodedMsg = user + " says " + msg;
var li = document.createElement("li");
li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);
});
connection.start().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();
});

来源: https://learn.microsoft.com/en-us/aspnet/core/tutorials/signalr?view=aspnetcore-2.1&tabs=visual-studio

SignalHub 中的 SendMessage 方法 你使用 Clients.All.ReceiveMessage 方法 我认为你应该使用Clients.All.Send方法(如果你使用的是aspnet核心,则使用SendAsync(

最新更新