问题
I'm leaning SignalR. How can I write a simple app so user can see server-time in real-time using Hub. Every 1 second, server will send time from server to connected clients
回答1:
you can do when you using thread.
Example Hub Class:
public class ServerTime : Hub
{
public void Start()
{
Thread thread = new Thread(Write);
thread.Start();
}
public void Write()
{
while (true)
{
Clients.settime(DateTime.Now.ToString());
Thread.Sleep(1000);
}
}
}
Example Script :
<script type="text/javascript">
$(document).ready(function () {
var time = $.connection.serverTime;
$("#btnTest").click(function () {
time.start();
});
time.settime = function (t) {
$("#Time").html(t);
};
$.connection.hub.start();
});
</script>
<div id="Time"></div>
<input id="btnTest" type="button" value="Test"/>
Thread will start working when you click btnTest. Thread sends message to page everysecond.
回答2:
Create a listener and RAISE AN EVENT when a NOTIFICATION is added :) Thus you would not have to continuously check the database :)
回答3:
In Global.asax in the Application_Start(object sender, EventArgs e) method create a background thread and start it. In that thread you will need to do this to get access to your hub:
IConnectionManager connectionManager = AspNetHost.DependencyResolver
.Resolve<IConnectionManager>();
dynamic clients = connectionManager.GetClients<ServerTime>();
clients.settime(DateTime.UtcNow.ToString());
NB DateTime.UtcNow is nearly always preferable since it doesn't leap around twice a year.
来源:https://stackoverflow.com/questions/9424967/how-can-i-make-a-server-time-app-with-signalr