2

We all know that signalR uses open connection to communicate with clients. I want to know how can I send message to clients without any request. For example in every amount of time or any event server pass data to clients.

The Hungry Dictator
  • 3,444
  • 5
  • 37
  • 53
moeen
  • 21
  • 1
  • 3

2 Answers2

1

Use this answer and run background task at your server-side.

Not inside the hub since they'r lifecycle is per-request.

Community
  • 1
  • 1
Igor Lizunov
  • 539
  • 5
  • 12
0

I think you need broadcast to all user. The following example shows a basic Code that broadcast a massage to all client.Each Time you call SendNotifications(" massage"), all users receive your massage.

 public class EmployeeHub : Hub
{

    public void SendNotifications(string message)
{
    Clients.All.receiveNotification(message);
} 
}

and web page:

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

Mostafa Esmaeili
  • 178
  • 1
  • 12
  • Whilst valid, this code won't work in the examples listed in the question (such as a timer or other server side event), so am downvoting. – thab Dec 29 '16 at 23:35
  • Btw, doesn't this code mean that any client can run the SendNotifications method on the server? – Worthy7 Feb 06 '19 at 01:17