【发布时间】:2016-01-18 13:22:41
【问题描述】:
我是 SignalR 的新手。当我实现以下代码时,数据库的变化并没有同时反映在浏览器中。
Javascript 代码
$(function () {
var notify = $.connection.notificationsHub;
notify.client.displayNotification = function (msg) {
console.log(msg);
$("#newData").html(msg);
};
// Start the connection.
$.connection.hub.start().done(function () {
alert("connection started");
}).fail(function (e) {
alert(e);
});
//$.connection.hub.start();
});
C# 代码 NotificationsHub 类
public void NotifyAllClients(string msg)
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationsHub>();
context.Clients.All.displayNotification(msg);
}
public void SendNotifications()
{
string message = string.Empty;
string conStr = ConfigurationManager.ConnectionStrings["MvcDemoDb"].ConnectionString;
using (SqlConnection connection = new SqlConnection(conStr))
{
string query = "SELECT [Message] FROM [dbo].[Messages]";
using (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();
}
}
}
NotificationsHub nHub = new NotificationsHub();
nHub.NotifyAllClients(message);
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
SendNotifications();
}
}
}
【问题讨论】:
-
可以分享一下hub代码吗?消息实际上是通过发送的吗?
-
public void NotifyAllClients(string msg) { IHubContext context = GlobalHost.ConnectionManager.GetHubContext
(); context.Clients.All.displayNotification(msg); } -
我想这是您对 SqlDependency 的使用不起作用....我从未使用过它们,但是:1)您不必启动 Sql Dependency 吗? 2)我看不到 SendNotifications 是如何被调用的(它设置了依赖)
-
@thab: 确认,你是对的,case 不再是问题了。
-
这可能是实例化的问题吗?为什么
SendNotifications实例化集线器类?这应该由 SignalR 进程隐式完成,不是吗?
标签: c# jquery asp.net-mvc model-view-controller signalr