【问题标题】:how to send message to client in signalR without client request如何在没有客户端请求的情况下在 signalR 中向客户端发送消息
【发布时间】:2017-05-10 21:24:58
【问题描述】:

我们都知道signalR 使用开放连接与客户端进行通信。 我想知道如何在没有任何请求的情况下向客户发送消息。例如,在每个时间量或任何事件服务器将数据传递给客户端。

【问题讨论】:

    标签: c# asp.net-mvc signalr


    【解决方案1】:

    使用this answer 并在您的服务器端运行后台任务。

    不在集线器内部,因为它们的生命周期是按请求进行的。

    【讨论】:

      【解决方案2】:

      我认为您需要向所有用户广播。以下示例显示了一个向所有客户端广播消息的基本代码。每次您拨打SendNotifications(" massage") 时,所有用户都会收到您的消息。

       public class EmployeeHub : Hub
      {
      
          public void SendNotifications(string message)
      {
          Clients.All.receiveNotification(message);
      } 
      }
      

      和网页:

          <body>
      <input id="text1" type="text" />
      <input id="button1" type="button" value="Send" />
      <ul id="discussion">
      </ul>
      <!--Reference the jQuery library. -->
      <script src="Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
      <!--Reference the SignalR library. -->
      <script src="Scripts/jquery.signalR-1.1.3.js" type="text/javascript"></script>
      <!--Reference the autogenerated SignalR hub script. -->
      <script src="signalr/hubs"></script>
      <script type="text/javascript">
          $(function () {
              // Declare a proxy to reference the hub.
              var notifications = $.connection.employeeHub;
              // Create a function that the hub can call to broadcast messages.
              notifications.client.receiveNotification = function (message) {
                  // alert(" says '" + message + "'");
                  // Html encode display name and message.                
                  var encodedMsg = $('<div />').text(message).html();
                  // Add the message to the page.
                  $('#discussion').append('<li>' + encodedMsg + '</li>');
              };
              // Start the connection.
              $.connection.hub.start().done(function () {
      
              });
          });
      </script>
      

      【讨论】:

      • 虽然有效,但此代码在问题中列出的示例中不起作用(例如计时器或其他服务器端事件),所以我不赞成。
      • 顺便说一句,这段代码不是意味着任何客户端都可以在服务器上运行 SendNotifications 方法吗?
      猜你喜欢
      • 1970-01-01
      • 2016-02-28
      • 1970-01-01
      • 1970-01-01
      • 2016-09-19
      • 1970-01-01
      • 2013-04-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多