1

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?

meJustAndrew
  • 6,011
  • 8
  • 50
  • 76
Thiru Arasu
  • 293
  • 1
  • 5
  • 23

1 Answers1

1

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.

meJustAndrew
  • 6,011
  • 8
  • 50
  • 76
  • thanks for the answer.it works fine..but after that ,i got an exception.how do i resolve it? Uncaught TypeError: Cannot read property 'client' of undefined – Thiru Arasu Nov 24 '16 at 15:46
  • 1
    @G.Thirunavukkarasu this is [another question](http://stackoverflow.com/questions/14146913/signalr-cannot-read-property-client-of-undefined) which targets more SignalR on the client side :) – meJustAndrew Nov 24 '16 at 15:49
  • Thanks Andrew. I will check that – Thiru Arasu Nov 24 '16 at 15:50