簡體   English   中英

SignalR向特定客戶端發送消息

[英]SignalR send message to specific client

我有一個帶靜態方法的集線器,它向當前所有用戶廣播通知。

public class NotificationHub : Hub
{
    private static string connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();

    [HubMethodName("sendNotifications")]
    public static void SendNotifications()
    {
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
        context.Clients.All.updateNotifications();
    }
}

我需要從前端javascript中輸入一些文本框輸入,例如10038,這是userID並將其發送到服務器類,例如

public class NotificationRepository
{
    private readonly string _connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

    public IEnumerable<Notifications> GetNotifications(int userID)
    {
        var notifications = new List<Notifications>();

        using (var connection = new SqlConnection(_connString))
        {
            connection.Open();
            using (var command = new SqlCommand(String.Format(@"SELECT [ID], [UserID], [Message] FROM [dbo].[Notification] WHERE [UserID] = {0}", userID), connection))
            {
                command.Notification = null;

                var dependency = new SqlDependency(command);
                dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

                if (connection.State == ConnectionState.Closed)
                {
                    connection.Open();
                }

                var reader = command.ExecuteReader();

                while (reader.Read())
                {
                    notifications.Add(item: new Notifications { ID = (int)reader["ID"], UserID = (int)reader["UserID"], Message = (string)reader["Message"] });
                }
            }
        }
        return notifications;
    }

    private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
    {
        if (e.Type == SqlNotificationType.Change)
        {
            NotificationHub.SendNotifications();
        }
    }
}

我為用戶ID定義的特定用戶返回一組通知,但我似乎無法弄清楚如何映射響應,以便我只向signalR中的特定客戶端返回通知。

如何將客戶端的連接ID映射到輸入的用戶ID?

我已閱讀signalR文檔,但它非常模糊,其他在線解決方案似乎無法解決此特定問題。

任何幫助將非常感激。

編輯

到目前為止,我已經嘗試使用IUserIdProvider,這是我到目前為止所做的,但這似乎不起作用。

在前端我設置了queryString如下

$.connection.hub.qs = "userId=" + $('#userText').val();

這是我的自定義IUserIdProvider

public class CustomUserIdProvider : IUserIdProvider
{
    public string GetUserId(IRequest request)
    {
         return request.QueryString["userId"];
     }
 }

這就是我的NotificationRepository的樣子

public class NotificationRepository
{
    private readonly string _connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

    public IEnumerable<Notifications> GetUserNotifications(string userID)
    {
        var notifications = new List<Notifications>();

        using (var connection = new SqlConnection(_connString))
        {
            connection.Open();
            using (var command = new SqlCommand(String.Format(@"SELECT [ID], [UserID], [Message] FROM [dbo].[Notification] WHERE [UserID] = {0}", userID), connection))
            {
                command.Notification = null;

                var dependency = new SqlDependency(command);
                dependency.OnChange += new OnChangeEventHandler((sender, e) => dependency_OnChange(sender, e, userID));

                if (connection.State == ConnectionState.Closed)
                {
                    connection.Open();
                }

                var reader = command.ExecuteReader();

                while (reader.Read())
                {
                    notifications.Add(item: new Notifications { ID = (int)reader["ID"], UserID = (int)reader["UserID"], Message = (string)reader["Message"] });
                }
            }
        }
        return notifications;
    }


    private void dependency_OnChange(object sender, SqlNotificationEventArgs e, string userID)
    {
        if (e.Type == SqlNotificationType.Change)
        {
            NotificationHub.SendNotifications(userID);
        }
    }
}

這是我的中心

public class NotificationHub : Hub
{
    private static string connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();

    [HubMethodName("sendNotifications")]
    public static void SendNotifications(string userId)
    {
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
        context.Clients.Client(userId).updateNotifications();
    }
}

所以我已經弄清楚了這個場景中的問題。 初始化queryString時

 $.connection.hub.qs = "userId=" + $('#userText').val(); 

在開始與集線器的連接之前,必須執行此操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM