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

M. *_*ris 6 c# signalr asp.net-core

有人知道 AspNet SignalR 中这段代码的等效 AspNetCore 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();
});
Run Code Online (Sandbox Code Playgroud)

Luk*_*eva 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;

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();
Run Code Online (Sandbox Code Playgroud)

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

注意:您的集线器还应该使用 SignalR (Microsoft.AspNetCore.SignalR) 的 .Net Core 包,以使其正常工作(根据我的经验)。


归档时间:

查看次数:

3622 次

最近记录:

7 年,8 月 前