Wednesday, February 19, 2014

Get Server time - Realtime Chat application on web in ASP.Net using SignalR Technology: Step 2

In previous post I have describe how to set up your project for SignalR with require software. Now I shall show to get server time and how can invoke a server method as request and how can get response with server time by calling client javascript method from server end.
Again here will be these main part of coding and here I am not changing anything in Startup.cs file. This code as it is.

using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(SignalRChat.Startup))]
namespace SignalRChat
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();
        }
    }
}

Next is ChatHub.cs and here is very small code as below:

using System;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace SignalRChat
{
    public class ChatHub : Hub
    {
        public void getservertime()        {
            Clients.Caller.serverresponse("This is server response. Server is calling client method from server.
Server time is: " + DateTime.Now.ToShortTimeString());
        }
    }
}

Here I have added on public method "getservertime()". Note here I have written all method in small letters and shall call this from client javascript in small letters only. Previously I have tested by writing in capital letters and have seen this is not working. So I would suggest to write these methods always in small letters only, to avoid difficulties.

"getservertime()" is very small method which will invoked by client on button press and this method will invoke a client's javascript method to send response to client. Note here I am writting 'Clients.Caller' to find out the client from where server method has invoked. If I need to call any different client's method (usually for chat application one user will send method to other, so one client will invoke server method and server method will call other client's client method. These things I shall show later) then there will be some different way, which I shall explain later. After 'Client.Caller' method name is coming that is "serverresponse()". This client method is passing argument and this will deliver server message to client.

Next I shall explain about client code and these all are HTML and Javascript only.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   
    <title>SignalR Simple Chat</title>
    <style type="text/css">
        .container {
            background-color: #99CCFF;
            border: thick solid #808080;
            padding: 20px;
            margin: 20px;
        }
    </style>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <!--Reference the jQuery library. -->
    <script src="Scripts/json2.js"></script>
    <script src="Scripts/jquery-1.10.2.js"></script>
    <script src="Scripts/jquery-1.10.2.min.js"></script>
   
    <!--Reference the SignalR library. -->
    <script src="Scripts/jquery.signalR-2.0.0.js"></script>
    <script src="Scripts/jquery.signalR-2.0.0.min.js"></script>
   
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="/signalr/hubs"></script>
    <!--Add script to update the page and send messages.-->
   
    <script type="text/javascript">
$(function () {
    // Declare a proxy to reference the hub.
    var chat = $.connection.chatHub;


    //Write your server response related code here
    chat.client.serverresponse = function (message) {
        $('#dvServerResponse').append(message);
    };

    // Start the connection.
    $.connection.hub.start().done(function () {
        //Write your server invoke related code here
        $('#btnHello').click(function () {
            console.log('call server');
            chat.server.getservertime();
        });
    });
});
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
<div>
    <div id="dvServerResponse"></div>   
    <input type="button" id="btnHello" value="Get Server Time" />   
</div>
    </div>
    </form>
</body>
</html>

These HTML and Javascript code I have written in ASP.Net file however this will work in normal HTML file as well.
Initial part is javascript library file referencing section. Here I am calling files in three steps, first JSON and JQeury files, next SignalR library and finally Hub files. Next starting custom java script codes.

In java script code firstly I have created a proxy of chatHub. Next code is

//Write your server response related code here
    chat.client.serverresponse = function (message) {
        $('#dvServerResponse').append(message);
    };

For time being you can assume this is standard syntax of creating client methods which will be called from server and within this cal implement client activities. For my case I am appending server response at div.

Other part of client codes as below

//Write your server invoke related code here
$('#btnHello').click(function () {
    console.log('call server');
    chat.server.getservertime();
});

This method will start executing once btnHello clicked and it will invoke server method to get server response. Here to invoke server method syntax like "chat.server.getservertime()" or "proxy-object.server.server-method()".

Finally result will displayed in client browser.

Here is the full code.

Thanks for reading my blog.



No comments: