我刚刚开始使用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
返回的新更新的文本。但它并没有反映在书页上。
Signalr不监视数据库的更改。当您在数据库中将用户设置为非活动状态时,它对Signalr没有任何意义。您的3个客户端仍然连接。
要得到想要的结果,在Hub
中添加如下内容public override OnConnected()
{
// Increase the active user count in the db
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<ServerHub>();
Clients.All.broadcastCount(DB.GetCount());
return base.OnConnected();
}
public override OnDisconnected()
{
//Decrease the connected user count in the db
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<ServerHub>();
Clients.All.broadcastCount(DB.GetCount());
return base.OnDisconnected();
}
当您连接和断开客户端时,集线器将通知已连接的客户端。
您需要以SignalR捕获的方式断开连接,因此您不能仅更改数据库中的标志。尝试从您的客户端调用$.connection.hub.stop();
。
此链接详细介绍。
如果您说在更新数据库后触发dependency_OnChange
事件,那么不调用SendNotifications();
,而是调用hub方法,特别是NotifyAllClients(...)