How can I make a server time app with SignalR

一曲冷凌霜 提交于 2019-12-25 01:23:16

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!