如何使用 AspNetCore SignalR 创建集线器代理

问题描述 投票:0回答:2

有人知道 AspNetCore SignalR 与 AspNet SignalR 中的这段代码等效吗?

Task.Factory.StartNew(() =>
{
    ////  var clients = Hub.Clients<RealTimeNotificationHub>();
    var connection = new HubConnectionContext("https://demohouse.go.ro:96/");
    var notificationmessag = new AlertMessage();
    notificationmessag.Content = "New message from " + device.Name + " <b>" +
                                 text + " </b>";
    notificationmessag.Title = alertType.Name;
    var myHub = connection.CreateHubProxy("realTimeNotificationHub");
    connection.Start().Wait();
    object[] myData = { notificationmessag.Title, notificationmessag.Content };
    myHub.Invoke("sendMessage", myData).Wait();
    connection.Stop();
});
c# asp.net-core signalr
2个回答
5
投票

添加 Nuget 包 Microsoft.AspNetCore.SignalR.Client 并尝试以下代码。我冒昧地使用了您帖子中的数据并将其转换为 .Net Core 版本。

//I'm not really sure how your HUB route is configured, but this is the usual approach.

var connection = new HubConnectionBuilder()
                .WithUrl("https://demohouse.go.ro:96/realTimeNotificationHub") //Make sure that the route is the same with your configured route for your HUB
                .Build();

var notificationmessag = new AlertMessage();
notificationmessag.Content = "New message from " + device.Name + " <b>" +
                                         text + " </b>";
notificationmessag.Title = alertType.Name;

object[] myData = { notificationmessag.Title, notificationmessag.Content };

connection.StartAsync().ContinueWith(task => {
    if (task.IsFaulted)
    {
        //Do something if the connection failed
    }
    else
    {
        //if connection is successfull, do something
        connection.InvokeAsync("sendMessage", myData);

    }).Wait();

您可以使用不同的方法来执行异步任务。

注意:您的 Hub 还应该使用 SignalR 的 .Net Core 包 (Microsoft.AspNetCore.SignalR) 才能使其正常工作(根据我的经验)。


0
投票
private HubConnection connection;
  
string url = "http://Server:port/Hub_Name";
        
connection = new HubConnectionBuilder()
            .WithUrl(url)
            .WithAutomaticReconnect()
             .Build();
       
 connection.StartAsync().ContinueWith(task => {
  if (task.IsFaulted)
     {
         //Do something if the connection failed
    }
     else
    {
        //if connection is successfull, do something
        connection.InvokeAsync("sendMessage", myData);

    }).Wait();
 }
© www.soinside.com 2019 - 2024. All rights reserved.