Click here to Skip to main content
15,881,172 members
Articles / Web Development / HTML
Article

Real Time Clock using SignalR

Rate me:
Please Sign up or sign in to vote.
3.05/5 (8 votes)
23 May 2016CPOL3 min read 29.4K   878   15   8
Real time communication between server and client using asp.net SignalR.

Introduction

Contents of this article

  1. What is real time communication.
  2. What is SignalR.
  3. Sample application.

What is real time communication

In real time communication, server is pushing data or notifying about update to the connected clients without waiting for a request from client. In real time communication client can also send data to server without pulling a full http request to server.  In real time communication the web browser looks like a desktop application.

What is SignalR

SignalR is an asp.net package to implement the real time communication functionality in a web application. It is available for VS2012 and later versions. It can be downloaded using NuGet. It's a combination of server side code and client side JavaScript.  It provide a easy way to implement real time communicate between server and client.  SignalR uses Web Socket to communicate and hides the socket implementation complexity to developers.  It used a Hub class in server side and jQuery in client side.

Sample application

The sample application shows how to install SignalR in an Asp.Net project and describe how to display a real time clock using SignalR. By selecting a country from the dropdown the clock displays the local time of that selected country in the browser and updates the time from server using SinganR not from client side using JavaScript. I have used VS2013 as IDE.

The Steps are as follows.

  1. Create an empty project using ASP.NET Web Application template.Image 1
  2. Install SingalR server and client packages using NuGet Packages Manager.Image 2
  3. The installed jQuery libraries are shown in below picture.Image 3
  4. Now add a SignalR Hub class into the project inside App_Code folder.Image 4
  5. Hub class contains public functions which are called by the client. Add a public function getTime in the Hub. This function will take a country time zone as a parameter and will convert the system datetime to the selected time zone and will push the converted datetime to the caller browser.
    public void getTime(string countryZone)
    {
        TimeZone currentZone = TimeZone.CurrentTimeZone;
        DateTime currentDate = DateTime.Now;
        DateTime currentUTC = currentZone.ToUniversalTime(currentDate);
        TimeZoneInfo selectedTimeZone = TimeZoneInfo.FindSystemTimeZoneById(countryZone);
        DateTime currentDateTime = TimeZoneInfo.ConvertTimeFromUtc(currentUTC, selectedTimeZone);
        Clients.Caller.setTime(currentDateTime.ToString("h:mm:ss tt"));
    }

    The client side code to call this function is written below.

    var hubProxy = $.connection.clockHub;
    hubProxy.server.getTime(countryZone);
  6. Now add a OWIN Startup class in the project.Image 5
  7. Add the following code to Startup class to map the SignalR with the project at startup.
    public void Configuration(IAppBuilder app)
    {
        app.MapSignalR("/signalr", new HubConfiguration());
    }
  8. Add a html page in the project to display the clock in browser. The client side script references are

    src="/Scripts/jquery-1.6.4.min.js"
    src="/Scripts/jquery.signalR-2.2.0.min.js"
    src="/signalr/hubs" 
    src="/Scripts/Client.js"

    Here first added a jQuery library and then added the jQuery SingalR library and then added reference of hubs script which is dynamically generated by the server.

  9. Now add a Client.js script file in the Scripts folder. Add the client side code which makes the client connected to the server and calls function from hub class. The sample client side JavaScript code shows below.
    var hubProxy = $.connection.clockHub;
    
    hubProxy.client.setTime = function (time) {
        $('#clock').html(time);
    };
    
    $.connection.hub.start().done(function () {
        setInterval(function () {
            hubProxy.server.getTime(countryZone);
        }, 1000);
    });

    In the about code first a proxy object is created and then assigned a callback function reference to the proxy client object which is fired when server push a update to the browser. Finally the start function is called to start the communication. After connection is successfully done, setInterval javascript function calls the getTime server function at every second until the browser is closed. The server then execute the hub function and send a response to the connected browser without refresh the full page. The server side code to push the update to the client is written below.

    Clients.Caller.setTime(currentDateTime.ToString("h:mm:ss tt"));

    Here client side function setTime is called to update the client. After getting a response the client execute the callback function and update the clock with new data.

  10. open the html page in the browser. The browser will display the clock shown below.Image 6

Conclusion

In conclusion SignalR is a so good and easy to implement tool for real time communication. It uses a hub class in server side and jQuery in client side. it works like remote procedure call between server and client. Real time communication is used in many applications like chat in browser, real time dashboard etc.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder http://softwarelandmarks.com/
Bangladesh Bangladesh
I am in Software Development for more than 12 years. I am expert on Microsoft Platform for Web Forms, MVC, MVC Core, Web API, Desktop App, PHP etc. I am also expert on jQuery, AngularJS, Bootstrap, Font Awesome, Telerik UI, Kendo UI etc. I know BackboneJS, KnockoutJS also. I am an article writer. I have many articles in CodeProject.

Email: khademulbasher@gmail.com

Comments and Discussions

 
QuestionPolling not necessary Pin
codefabricator25-May-16 9:08
codefabricator25-May-16 9:08 
AnswerRe: Polling not necessary Pin
Khademul Basher26-May-16 0:45
Khademul Basher26-May-16 0:45 
Yes we can create loop and push the content at every second from server to client. But in this example I have created the loop in client. The server is idle in this case.
GeneralRe: Polling not necessary Pin
Nitij26-May-16 6:50
professionalNitij26-May-16 6:50 
GeneralRe: Polling not necessary Pin
Khademul Basher26-May-16 21:24
Khademul Basher26-May-16 21:24 
GeneralRe: Polling not necessary Pin
Nitij26-May-16 23:41
professionalNitij26-May-16 23:41 
GeneralRe: Polling not necessary Pin
Khademul Basher29-May-16 21:52
Khademul Basher29-May-16 21:52 
QuestionMisleading term Pin
webmaster44224-May-16 7:44
webmaster44224-May-16 7:44 
AnswerRe: Misleading term Pin
Khademul Basher24-May-16 23:31
Khademul Basher24-May-16 23:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.