我倾向于 SignalR。如何编写一个简单的应用程序,以便用户可以使用 Hub 实时查看服务器时间。每隔 1 秒,服务器会将时间从服务器发送到连接的客户端
问问题
2672 次
3 回答
3
您可以在使用线程时执行此操作。
示例集线器类:
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);
}
}
}
示例脚本:
<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"/>
当您单击 btnTest 时,线程将开始工作。线程每秒向页面发送消息。
于 2012-02-27T07:11:17.480 回答
0
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.
于 2012-04-09T06:21:16.940 回答
0
创建一个侦听器并在添加通知时引发一个事件:) 因此您不必不断检查数据库:)
于 2012-04-01T17:56:55.043 回答