根据各种资源,signalr
代码应该可以工作,但我无法将通知从服务器发送到客户端。这是 html/javascript 部分:
<script src="/Scripts/jquery-1.6.4.min.js"></script>
<script src="/Scripts/jquery.signalR-2.2.1.min.js"></script>
<script src="/signalr/js"></script>
<script type="text/javascript">
$(function () {
var cHub = $.connection.cHub;
$.connection.hub.logging = true;
cHub.client.sendMessage = function (content) {
$("#container-hub").append($("<p />").html(content));
};
$.connection.hub.start().done(function() {
$('[id$=bGo]').click(
function() {
cHub.server.send('Sync process started');
});
});
});
</script>
<div id="container-hub" style="background: red; height: 100px; width: 100%;"></div>
Hub.cs 类:
using Microsoft.AspNet.SignalR;
namespace CMS.Objects
{
public class CHub : Hub
{
public void Send(string message)
{
// Call the broadcastMessage method to update clients.
Clients.All.sendMessage(message);
}
}
}
Startup.cs 类:
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(CMS.CStartup))]
namespace CMS
{
public class CStartup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
这是我如何调用方法sendMessage
方法:
private void ShowMessage(string message)
{
var clients = GlobalHost.ConnectionManager.GetHubContext<CHub>().Clients;
clients.All.sendMessage(message);
}
单击按钮时bGo
,消息将附加到container-hub
div 中,但当我调用sendMessage
方法时没有任何内容。
编辑
一些额外的发现;当我sendMessage
从OnConnected
方法中调用它时:
public override Task OnConnected()
{
Clients.All.sendMessage("Connection Initialised");
return base.OnConnected();
}