【问题标题】:SignalR sending data from clientSignalR 从客户端发送数据
【发布时间】:2018-09-27 00:05:53
【问题描述】:

我想使用 SignalR 将数据从服务器端发送到客户端。 我在这里有一个Task 来迭代这项工作。此作业从 SignalR 继承 Hub 类,它发送迭代的当前进度。但是它不会返回我从服务器端发送的数据。

public async Task loop()
{
    ProgressHub p = new ProgressHub();

    for(var i = 0; i < 100; i++){
        await p.SendProgress(i, 100);
    }
}

public async Task SendProgress(int currentRow, int rowCount)
{
   string message = "Initializing and Preparing...";
   int percent = (currentRow * 100) / rowCount;


    var hubContext = GlobalHost.ConnectionManager.GetHubContext<ProgressHub>();
    var percentage = (currentRow * 100) / rowCount;

    hubContext.Clients.All.AddProgress(message, percent + "%");

    await Task.Delay(100);
}

在控制器上调用循环方法。

public async Task<JsonResult> CallSignalR()
{
    await loop();

    return Json("", JsonRequestBehavior.AllowGet);
}

在 JS 上调用 SignalR

var progressNotifier = $.connection.progressHub;

console.log(progressNotifier);

progressNotifier.client.addProgress = function (currentRow, rowCount) {

console.log(currentRow);
};

$.connection.hub.start();

【问题讨论】:

  • console.log(currentRow) 向控制台写入了什么?
  • @mjwills 它什么也不返回。但是progressNotifier返回的是连接的属性。

标签: c# asp.net-mvc signalr


【解决方案1】:

尝试以不同的方式定义和分配您的功能。例如如下:

var progressNotifier = $.connection.progressHub;
console.log(progressNotifier);

progressNotifier.client.addProgress = onAddProgress;

function onAddProgress(currentRow, rowCount) {
    console.log(currentRow);
};

$.connection.hub.start();

我还建议您对这些函数使用单个参数,我过去遇到过使用多个参数的问题。您可以传递单个 Json 消息并在以后反序列化它。

【讨论】:

    猜你喜欢
    • 2013-07-18
    • 1970-01-01
    • 1970-01-01
    • 2015-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-19
    相关资源
    最近更新 更多