【发布时间】:2017-04-08 04:38:10
【问题描述】:
我想使用 signalR 从服务器调用通知特定客户端,但它不起作用。我的代码已成功执行,但客户端没有收到来自服务器的任何调用。
但这对所有客户都有效。
var hubContext = GlobalHost.ConnectionManager.GetHubContext<ProcessStatusNotifyHub>();
hubContext.Clients.All.notify("Got it!");
但这不适用于特定客户 [更新代码] 以下代码用chat.cshtml编写
$(function () {
// Reference the auto-generated proxy for the hub.
var chat = $.connection.processStatusNotifyHub;//chatHub;
chat.client.notify = function (msg) {
alert(msg);
}
// Start the connection.
$.connection.hub.start().done(function () {
var myClientId = $.connection.hub.id;
console.log('connected: ' + myClientId);
$('#sendmessageToClient').click(function () {
//chat.server.send('imdadhusen', 'This is test text');
$.ajax({
url: '@Url.Action("Send", "PushNotification")',
type: 'POST',
data: { 'clientID': myClientId },
dataType: 'json',
success: function (result) {
alert(result.status);
}
});
});
});
});
以下代码是在Controller中编写的
[HttpPost]
public ActionResult Send(string clientID)
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<ProcessStatusNotifyHub>();
//hubContext.Clients.All.notify("Got it!");
hubContext.Clients.User(clientID).notify("Got it!");
responseResult result = new responseResult();
result.status = "OK";
result.message = "Notification sent successfully";
return Json(result, JsonRequestBehavior.AllowGet);
}
我已尝试调试它在 .cstml 或控制器上显示正确的客户端 ID 值的代码。例如clientid : 0fdf6cad-b9c1-409e-8eb7-0a57c1cfb3be
您能帮我从服务器向特定客户端发送通知吗?
【问题讨论】:
-
你能提供完整的控制器吗?您提供的代码不清楚 connectionId 是否在您尝试执行的操作的正确范围内。
-
@Steve 我已经更新了代码供您参考,请告诉我您仍然需要更多详细信息。
-
感谢更新。调试服务器时,clientID 是否设置为您期望的值?
-
实际上客户端 ID 已成功传递给控制器,并且该语句也被执行,没有任何错误
hubContext.Clients.User(clientID).notify("Got it!");但客户端我没有在函数内收到消息chat.client.notify. -
如果 clientID 是 SignalR 连接 ID,我想你想要
Clients.Client(clientID)而不是Clients.User(clientID)
标签: c# asp.net-mvc-4 signalr