【发布时间】:2015-07-24 13:27:39
【问题描述】:
我刚开始使用 SignalR,想试用实时通知。目标是继续在网页上显示更新的消息。
有一个数据库表 - DummyData,其中有一列 Message。此表只有一条记录 - Hello
页面加载时,会显示“Hello”。
然后我在 sql server 2012 中手动运行命令
update DummyData set Message='hello world',但网页中没有更新消息。
aspx:
<script>
$(function () {
var notify = $.connection.notificationsHub;
$.connection.hub.start().done(function () {
notify.server.notifyAllClients();
});
notify.client.displayNotification = function (msg) {
$("#newData").html(msg);
};
notify.client.stopClient = function () {
$.connection.hub.stop();
};
});
</script>
<span id="newData"></span>
aspx.cs:
public string SendNotifications()
{
string message = string.Empty;
using (SqlConnection connection = new SqlConnection(conStr))
{
string query = "SELECT [Message] FROM [dbo].[DummyData]";
SqlCommand command = new SqlCommand(query, connection)
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
message = reader[0].ToString();
}
}
return message;
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
SendNotifications();
}
}
NotificationsHub.cs
public class NotificationsHub : Hub
{
Messages obj = new Messages();
public void NotifyAllClients(string msg)
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationsHub>();
context.Clients.All.displayNotification(msg);
}
public override System.Threading.Tasks.Task OnConnected()
{
NotifyAllClients();
return base.OnConnected();
}
public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
{
NotifyAllClients();
return base.OnDisconnected(stopCalled);
}
}
global.asax:
protected void Application_Start(object sender, EventArgs e)
{
SqlDependency.Start(Constr);
}
当我运行 tsql update 命令时,断点首先位于dependency_OnChange,我可以看到从SendNotification 返回的新更新文本。但它没有反映在页面上。感觉就像我快到了,但缺少一些东西。
【问题讨论】:
-
作为提示,请尝试覆盖集线器上的
OnConnected、OnDisconnected和OnReconnected事件。放置一些断点以查看它们发生的时间和地点 -
当您说手动停用用户时,您是如何做到的?
-
你的
app.MapSignalR();中有Startup.cs -
@lzzy。是的,我做到了。我也显示了初始计数。
-
如果您在调试时遇到断点,那么这是一个好的开始。尝试在页面上连接一个调用 JS 函数
$.connection.hub.stop();的按钮。notify.client.stopClient = function () {这条线是错的,你只需要停止连接。我建议多阅读SignalR Docs