如何在没有客户端请求的情况下在signalR中向客户端发送消息

问题描述:

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

您可以参考此链接Reference

我想你需要广播给所有的用户。以下示例显示了向所有客户端广播按摩的基本代码。每次您拨打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> 

+0

虽然有效,但此代码在问题中列出的示例(例如计时器或其他服务器端事件)中不起作用,所以下调投票。 – thab

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

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

+0

这个答案是正确的 – thab