1
我們正在向Asp.net Web應用程序添加實時推送通知。使用SignalR和SqlDependency進行個性化推送通知
我可以向登錄網站的所有用戶廣播一條消息。
但我無法根據插入數據庫表中的值僅向一個特定用戶發送通知。
當我嘗試這樣做時,它更新所有當前登錄的客戶端。
我的代碼示例如下:
的SqlDependency組件:
Public Sub RegisterNotification(ByVal currentTime As DateTime)
Try
Dim conStr = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim sqlCommand = "SELECT [seq_id],[user_id],[create_timestamp],[alert_read] FROM [dbo].[tblAlerts] WHERE [alert_read]=0 AND [create_timestamp] > @AddedOn"
Using con As New SqlConnection(conStr)
Dim cmd As New SqlCommand(sqlCommand, con)
cmd.Parameters.AddWithValue("@AddedOn", currentTime)
If con.State <> Data.ConnectionState.Open Then
con.Open()
End If
cmd.Notification = Nothing
Dim dependency As New SqlDependency(cmd)
AddHandler dependency.OnChange, AddressOf sqlDep_OnChange
Using reader As SqlDataReader = cmd.ExecuteReader()
Do nothing here
End Using
End Using
Catch ex As Exception
Throw ex
End Try
End Sub
Sub sqlDep_OnChange(ByVal sender As Object, ByVal e As SqlNotificationEventArgs)
Try
If e.Info = SqlNotificationInfo.Insert Then
Dim notificationHub = GlobalHost.ConnectionManager.GetHubContext(Of NotificationHub)
Dim userid = Membership.GetUser.ProviderUserKey
notificationHub.Clients.All.notify(userid)
End If
Dim depend = DirectCast(sender, SqlDependency)
RemoveHandler depend.OnChange, AddressOf sqlDep_OnChange
RegisterNotification(DateTime.UtcNow)
Catch ex As Exception
End Try
End Sub
通知基地代碼
Public Class NotificationHub
Inherits Hub
Public Sub showdata(ByVal obj As Object)
Try
Dim userobj = obj
Dim notificationHub = GlobalHost.ConnectionManager.GetHubContext(Of NotificationHub)
Dim count = 0
take count from database for userid in the object
notificationHub.Clients.All.setcount(count)
Catch ex As Exception
End Try
End Sub
End Class
SignalR JS代碼
$(function() {
// signalr js code for start hub and send receive notification
var notificationHub = $.connection.notificationHub;
notificationHub.client.setCount = function (data) {
$('span.count').html(data);
}
$.connection.hub.start().done(function() {
console.log('Notification hub started');
});
//signalr method for push server message to client
notificationHub.client.notify = function (message) {
if (message) {
notificationHub.server.showdata(message);
}
}
})
我也注意到這裏還有一件事是sqlDep_OnChange事件被多次調用,如果我已經在多個瀏覽器中打開應用程序。