Search code examples
asp.netsignalrsignalr-hub

periodically sending messages to all clients using signalr


I want to send some data from server to all connected clients using hubs after a specific interval. How can I accomplish this using signalr hubs.


Solution

  • Just add

    Thread.Sleep(5000);
    

    in your send Method.

    Ex:

        public void Send(string name, string message)
        {
            Thread.Sleep(5000);
            //call the broadcast message to upadate the clients.
            Clients.All.broadcastMessage(name, message); 
        }
    

    Hope it helps.

    Edit

    The following code renders the current time for every 5 seconds.

    Here is script for it:

    <script type="text/javascript">
        $(function () {
            $.connection.hub.logging = true;
            $.connection.hub.start();
            // Declare a proxy to reference the hub.  
            var chat = $.connection.chatHub;
    
            //Appending the responce from the server to the discussion id
            chat.client.currentTime = function (time) {
                $('#discussion').append("<br/>" + time + "<br/>");
            };
    
            // Start the connection. 
            $.connection.hub.start().done(function () {
    
                //Call the server side method for every 5 seconds
                setInterval(function () {
                    var date = new Date();
                    chat.client.currentTime(date.toString());
                }, 5000);
            });
    
        }); 
    </script>
    
    <div id="discussion"></div>
    

    And on the HubClass write the following:

    public class ChatHub: Hub
       {
            public void currentTime(string date)
            {
                Clients.All.broadCastTime(date);
            }
       }