Search code examples
javascriptc#signalrtimedelayclients

How do i receive messages periodically from Signalr to all Clients automatically ,without client input?


I am new to SignalR. I need to send message from SignalR to all connected clients automatically with some delay without client input ?

The above process has to be repeated, while recursively?

Is it possible?

Without client input, the SignalR can send messages automatically to clients repeatedly?

This is my JavaScript cleint code:

$(function () {
    var chat = $.connection.timehub;
    $.connection.hub.start();
    chat.client.broadcastMessage = function (current) {
        var now = current;
        console.log(current);
        $('div.container').append('<p><strong>' + now + '</strong></p>');
    }
};

and this is my Timehub

public class timehub : Hub
{
    public void Send(string current)
    {
        current = DateTime.Now.ToString("HH:mm:ss:tt");
        Clients.All.broadcastMessage(current);

        System.Threading.Thread.Sleep(5000);
        Send(current);
    }
}

and this is my Owin Startup Class:

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

    }
}

Could anyone provide me an solution for this?


Solution

  • If you will keep calling the Send() method recursively like you do right now, you will get a stackoverflow exception. Just wrap the code inside the method in a while(true) loop:

    public class timehub : Hub
    {
        public void Send()
        {
            while(true)
            {
                var current = DateTime.Now.ToString("HH:mm:ss:tt");
                Clients.All.broadcastMessage(current);
                System.Threading.Thread.Sleep(5000);
            }
        }
    }
    

    I would suggest moving the Send() method to another thread, because the current thread will get stuck forever in this while loop.