G.Thirunavukkarasu G.Thirunavukkarasu - 8 days ago 4
C# Question

SignalR: How do i push the contents from server to client automatically in signalr?

I am creating a .net web Application with signalR. My Requirement is ,when the Client starts hosting,the server automatically push the current time value to client with some time delay recursively. i wrote the code.But the signalR couldn't automatically send the message to client?

i thought,signalR need some input from client. I knew each time signalr expect input from client via hub.is there anyway to call client automatically in server?

By the way i wrote code.is it correct?

this is my HUB:-

public class timeHub : Hub
{
public void Send()
{

while(true)
{
var current = DateTime.Now.ToString("HH:mm:ss:tt");
Clients.All.broadcastMessage(current);
Console.WriteLine(current);
Console.ReadLine();
System.Threading.Thread.Sleep(5000);

}
}
}


My Owin startup Class:-

[assembly: OwinStartup(typeof(Time.Startup))]

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

}
}
}


My Client side javascript Code is:-

<div class="container">
</div>
<script src="Scripts/jquery-1.6.4.min.js"></script>
<script src="Scripts/jquery.signalR-2.2.1.min.js"></script>
<script src="signalr/hubs"></script>
<script type="text/javascript">
$(function () {
var chat = $.connection.timeHub;
chat.client.broadcastMessage = function (current) {
var now = current;
console.log(current);
$('div.container').append('<p><strong>'
+ now + '</strong></p>');
};
$.connection.hub.start().done(function () {

chat.server.send();
});
});
</script>


How do i push the cotents from server to client automatically,without client call in signalr?

Could Anyone provide me an solution to solve this problem?

My Empty Client Page

Answer

What I'm seeing is your code is that nothing is calling your timeHub:Send() method. You've defined a hub and defined an infinitely looping Send function however it looks as though you've forgotten to start your Send() pump.
You need to call it! Remember tho that as your Send() function will never return, whatever thread calls Send() will be blocked.

I'd recommend starting a Task so that your main thread is not blocked by the initial call to Send().

Good luck!

Comments