如何使用Signalr IhubContext仅向呼叫者广播

时间:2016-10-01 18:17:23

标签: c# asp.net signalr

我有一个Signalr Hub,用于在将新数据插入数据库时​​通知用户

public class NotifyHub : Hub
{
    public void NotifyAllClients(string source, string msg)
    {
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotifyHub>();
        context.Clients.All.displayNotification(source, msg);

    }
}

客户端

   $(function () {
        var notify = $.connection.notifyHub;

        notify.client.displayNotification = function (source,msg) {
            new PNotify({
                title: source,
                text: msg,
                type: 'success',
                styling: 'bootstrap3'
            });
        };
        $.connection.hub.logging = true;
        $.connection.hub.start();
    });

客户端default.aspx代码隐藏

protected void Page_Load(object sender, EventArgs e)
{


    SendNotifications();
}


public void SendNotifications()
{
    string message = string.Empty;
    string source = string.Empty;
    string conStr = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString;

    using (SqlConnection connection = new SqlConnection(conStr)) {
        string query = "SELECT [Source], [MSG] FROM [dbo].[LOG_EVENT] ORDER BY LOG_DATE DESC, LOG_TIME DESC";

        using (SqlCommand command = new SqlCommand(query, connection)) {
            command.Notification = null;
            SqlDependency dependency = new SqlDependency(command);
            dependency.OnChange += dependency_OnChange;

            connection.Open();
            SqlDataReader reader = command.ExecuteReader();

            if (reader.HasRows) {
                reader.Read();
                source = reader(0).ToString();
                message = reader(1).ToString();
            }
        }
    }
    NotifyHub nHub = new NotifyHub();

    nHub.NotifyAllClients(source, message);
}

但是当用户连接到集线器时,这会通知所有客户端它会导致向使用网页的所有用户弹出多个通知。

我知道我可以使用caller属性通知只有来电者,但此属性不适用于IHubContext我无法找到解决此问题的任何解决方案

0 个答案:

没有答案