如何使用实时(SignalR)更新数据

本文关键字:更新 数据 SignalR 何使用 实时 | 更新日期: 2023-09-27 18:25:10

我写这篇文章是为了寻求有关使用SignalR创建实时数据更新的帮助。我目前在客户端遇到问题,无法呈现数据内容。

我有一个测试过的query命令,它似乎正在返回数据。这让我相信,我的客户端代码可能不正确。

<script src="~/Scripts/jquery-1.8.2.min.js" type="text/javascript" ></script>
<script src="~/Scripts/jquery.signalR-2.0.1.min.js" type="text/javascript" ></script>
<script src="~/signalr/hubs" type="text/javascript" ></script>
<script type="text/javascript">
$(function () {
    // Declare a proxy to reference the hub.          
    var notifications = $.connection.NotificationHub;
    // Create a function that the hub can call to broadcast messages.
    notifications.client.recieveNotification = function (role, descrip) {
        // Add the message to the page.                    
        $('#spanNewMessages').text(role);
        $('#spanNewCircles').text(descrip);
    };
    // Start the connection.
   $.connection.hub.start().done(function () {
        notifications.server.sendNotifications(function () {
            alert("does it work");
            });
    }).fail(function (e) {
        alert(e);
    });
 </script>
 <h1>New Notifications</h1>
 <div>
<b>New <span id="spanNewMessages"></span> role.</b><br />
<b>New<span id="spanNewCircles"></span> descrip.</b><br />
 </div>

集线器类别:

  [HubName("NotificationHub")]
  public class notificationHub : Hub
  {
    string role = "";
    string descrip = "";
    [HubMethodName("sendNotifications")]
    public void SendNotifications()
    {
        using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["dummyConnectionString"].ConnectionString))
        {
            string query = "SELECT [role],[description] FROM [dbo].[User]";
            connection.Open();
            using (SqlCommand command = new SqlCommand(query, connection))
            {                  
                command.Notification = null;                
                DataTable dt = new DataTable();
                SqlDependency dependency = new SqlDependency(command);
                dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
                if (connection.State == ConnectionState.Closed)
                    connection.Open();                
                var reader = command.ExecuteReader();
                dt.Load(reader);
                if (dt.Rows.Count > 0)
                {
                    role = dt.Rows[0]["role"].ToString();
                    descrip = dt.Rows[0]["description"].ToString();
                }
            }  
        }
     Clients.All.RecieveNotification(role, descrip);
    }
    private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
    {
        if (e.Type == SqlNotificationType.Change)
        {
            notificationHub nHub = new notificationHub();
            nHub.SendNotifications();
        }
    }
}

启动CLass:

 using Microsoft.Owin;
 using Owin;
 using WebApplication2;
 namespace WebApplication2
 {
   public class Startup
    {
       public void Configuration(IAppBuilder app)
       {
        app.MapSignalR();
       }
    }
  }

有没有人,请提供一些助手,告诉我这项任务可能出错的地方。非常感谢。

如何使用实时(SignalR)更新数据

我模拟了你的应用程序。您的问题是您正在从集线器操作返回字符串:

public string SendNotifications()
{
    return context.Clients.All.RecieveNotification(role, descrip);
}

这应该是无效的(您没有返回任何内容,而是实际调用客户端),并且您也不需要使用GlobalHost来获取此处的上下文,只有当上下文不可用时(即从服务器调用集线器)。尝试进行以下更改:

[HubMethodName("sendNotifications")]
public void SendNotifications()
{
    //using...
    //IHubContext context = GlobalHost.ConnectionManager.GetHubContext<notificationHub>();
    //return context.Clients.All.RecieveNotification(role, descrip);
    Clients.All.RecieveNotification(role, descrip);
}

Clients.All...处放置一个断点,看看它是否被触发。如果这些更新解决了您的问题,请告诉我。