G.Thirunavukkarasu G.Thirunavukkarasu - 15 days ago 6
C# Question

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

Answer

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.