[英]Sending message from server to specific client is not working using SignalR 2 and MVC 4.0
[英]SignalR message not working when sending from server side to client
这是我的HTML:
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.khaosHub;
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (message) {
// Html encode display name and message.
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li>' + encodedMsg + '</li>');
};
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
console.log("sending");
// Call the Send method on the hub.
chat.server.send("something");
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
</script>
我的中心:
public class KhaosHub : Hub
{
public void Send(string message)
{
Clients.All.broadcastMessage(message);
}
}
当我点击#sendmessage
我Send
的方法KhaosHub
被触发,我已经使用断点验证和我的消息不会被发送到通过DIV broadcastMessage
。
注意:上例中未包含对app.MapSignalR
调用,因为我知道它在客户端运行。
我遇到的问题是,当我从某些后端代码调用broadcastMessage
,它不起作用。 我通过以下方式致电:
var context = GlobalHost.ConnectionManager.GetHubContext<KhaosHub>();
context.Clients.All.broadcastMessage("some message");
当我调试Clients.All
属性时,我看不到任何客户端(我不知道是否应该这样做,但以为我会添加该信息。
有任何想法吗?
编辑:这是我的集线器的启动类:
[assembly: OwinStartup(typeof (Startup))]
namespace CC.Web
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
谢谢你的问题。 在评论之后,我也跟踪了自己的问题,也没有从GlobalHost.ConnectionManager中获取正确的hubcontext。
为了解决这个问题,我专门在GlobalHost上设置了DependencyResolver并将此解析器传递给用于MapSignalR的HubConfiguration。
在代码中是:
Microsoft.AspNet.SignalR.GlobalHost.DependencyResolver =
New Microsoft.AspNet.SignalR.DefaultDependencyResolver
app.MapSignalR(
New Microsoft.AspNet.SignalR.HubConfiguration With
{.Resolver = Microsoft.AspNet.SignalR.GlobalHost.DependencyResolver})
您可能需要将此VB.Net代码转换为C#。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.