Tuesday, December 29, 2015

SignalR Implementation in HTML Page

Html Page :

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <label id="serverDate"></label>
    <button id="initTimer">Start Timer</button>

    <!--Script references. -->
    <script src="Scripts/jquery-1.6.4.min.js"></script>
    <script src="Scripts/jquery.signalR-2.0.0.js"></script>

    <!--Reference the autogenerated SignalR hub script. -->
    <script src="signalR/hubs"></script>
    <script type="text/javascript">
        $(function () {
            // Declare a proxy to reference the hub.
            var hub = $.connection.demoHub;

            hub.client.serverDateTimeInfo = function (time) {
                $("#serverDate").text(time);
            };

            $.connection.hub.start().done(function () {
                alert('Server connected');

                hub.server.getServerDatetime();

                $("#initTimer").click(function () {
                    hub.server.initTimer();
                });
            });
        });
    </script>
</body>
</html>

SignalR Hub Page :

using Microsoft.AspNet.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Timers;
using System.Web;

namespace SignalRChat
{
    public class DemoHub :Hub
    {
        public void GetServerDatetime()
        {
            SendNotification();
        }

        private void SendNotification()
        {
            try
            {
                Clients.Caller.serverDateTimeInfo(DateTime.Now.ToString());
            }
            catch { }
        }

        public void InitTimer()
        {
            Timer timer = new Timer(1000);
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer.AutoReset = true;
            timer.Enabled = true;
        }

        public void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            SendNotification();
        }
        
    }
}

No comments: