简体   繁体   English

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

[英]How to update data using real-time (SignalR)

I am writing to seek help, in regards creating a real-time data update using SignalR. 我正在写信寻求使用SignalR创建实时数据更新方面的帮助。 I am currently having issue on the client-side, where I am unable to render the data content. 我目前在客户端无法播放数据内容时遇到问题。

I have a tested the query command and it seems to be returning data. 我已经测试过查询命令,它似乎正在返回数据。 This leads me to believe, that my client-side code, maybe incorrect. 这使我相信,我的客户端代码可能不正确。

<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>

Hub Class: 集线器类别:

  [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();
        }
    }

}

StartUp CLass: 启动CLass:

 using Microsoft.Owin;
 using Owin;
 using WebApplication2;

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

Could anyone, please provide some assistant, to where I may be going wrong with this task. 任何人都可以提供一些助手,以解决我可能在此任务上出错的地方。 Thank you. 谢谢。

I mocked up your app. 我模拟了您的应用。 Your issue was you are returning a string from your hub action: 您的问题是您要从中心操作返回一个字符串:

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

this should be void (you aren't returning anything, but actually calling the clients), and you also don't need to use GlobalHost to get the context here, only when the context isn't available (IE calling the hub from the server). 这应该是无效的(您不返回任何东西,但实际上是在调用客户端),并且您也不需要使用GlobalHost在此处获取上下文,仅当上下文不可用时(即从服务器)。 Try making these changes: 尝试进行以下更改:

[HubMethodName("sendNotifications")]
public void SendNotifications()
{
    //using...

    //IHubContext context = GlobalHost.ConnectionManager.GetHubContext<notificationHub>();
    //return context.Clients.All.RecieveNotification(role, descrip);

    Clients.All.RecieveNotification(role, descrip);
}

Put a breakpoint at Clients.All... and see if it is being triggered. Clients.All...Clients.All...一个断点,然后查看是否被触发。 Let me know if these updates fix your issue. 让我知道这些更新是否解决了您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM