Tuesday, 8 November 2016

SignalR Chat Application in Asp.net MVC:

General way of communication is the Request and Response model.But now the communication model has been changed to Comet model.Which is generally adopted by the most recent chatting applications.

Types of bi-directional communication:
1)Forever Frame (Script Tag or 'Iframe'or stream)
2)Ajax Long Polling
3)Server Sent Event(text/event)
4)Websocket (Html 5 Supported Browsers)

Comet Model:
SignalR is built upon all the above types.SignalR implements Comet model using any one way of types.We need not have to worry about all these types of transport mechanism , SignalR will check the capability of the browser during the communication and as per the capability it will follow any one type (transport mechanism) of communication.In this model we have the facility to force a connection to use any one of the mechanism.

To work with SignalR we require some steps :
1)A Hub (a Class to which each client will communicate)
2)Creating Server Method
3)Connecting to Hub By object (Through Proxy Classes) from client 
4)Creating Object of the Hub class at client side
5)Client Calling the Server Method
6)Client Method(JS Function) which will be called by server method
7)Calling Client method by Servermethod(callback method) which are in connection
  (That means the message passed to server method by one client will be passed to all connected client methods)

The message broadcast which is discussed above is a method of broadcasting from inside the Hub,but it is possible to broadcast from outside the Hub by outsider and it is also possible that you can make the client specific broadcast.If you want to specify a different name for clients to use, add the HubName attribute before the Hub Class. When you use a HubName attribute, there is no name change to camel case on JavaScript clients,you can use the PascalCase.


Group Chat Application In Asp.Net MVC 5 :
step 1: Create an Asp.net MVC application with no Authentication named SignalRChat.

step 2: Open the Tools | Library Package Manager | Package Manager Console and run the following command. This step adds to the project a set of script files and assembly references that enable SignalR functionality.

install-package Microsoft.AspNet.SignalR

Or goto Manage NuGet packages and download the SignalR Components.

step 3: Now go to Solution Explorer, right-click the project, select Add | New Folder, and add a new folder named Hubs.Right-click the Hubs folder, click Add | New Item, select the Visual C# | Web | SignalR node in the Installed pane, select SignalR Hub Class (v2) from the center pane, and create a new hub named ChatHub.cs.

step 4: Then Write the code as follows ,

using System;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;

namespace SignalRChat
{
    [HubName("mychatHub")] //To be called from client side
    public class ChatHub : Hub
    {
        public void Send(string name, string message)
        {
   //Called by hub from client
            Clients.All.addNewMessageToPage(name, message);
        }
    }
}

step 5: Create a OWIN Statup class named Startup.cs and write the code as follows ,

using Owin;
using Microsoft.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();
        }
    }
}

step 6: Now create a controller and put an action method named chat as follows ,

public ActionResult Chat()
{
     return View();
}


step 7: Create a View(applying layoutpage) for the action Chat and put the following code inside the view ,

@{
    ViewBag.Title = "Chat";
}

<h2>Chat</h2>

<div class="container">
    <input type="text" id="message" />
    <input type="button" id="btnsendmessage" value="Send" />
    <input type="hidden" id="displayname" />
    <ul id="discussion"></ul>
</div>
@section scripts {
    
    <!-- If layout page is not applyed then put a reference of jQuery -->
    <script src="~/Scripts/jquery.signalR-2.2.0.js"></script>

    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/signalr/hubs"></script>

    <!--SignalR script to update the chat page and send messages.-->

    <script>
        $(function () {

            // Reference the auto-generated proxy for the hub.
            var chat = $.connection.mychatHub;

            // The function to be called by the hub to display messages.
            chat.client.addNewMessageToPage = function (name, message) {
                // Adding the message to the page.
                $('#discussion').append('<li><strong>' + htmlEncode(name)
                    + '</strong>: ' + htmlEncode(message) + '</li>');
            };

            // Store the username  to prefix before messages.
            $('#displayname').val(prompt('Enter your name:', ''));

            // Set initial focus to message input box.
            $('#message').focus();

            // Start the connection.
            $.connection.hub.start().done(function () {

                $('#btnsendmessage').click(function () {
                    // Call the Send method present in the hub.
                    chat.server.send($('#displayname').val(), $('#message').val());
                    // Clear text box and reset focus for next comment.
                    $('#message').val('').focus();
                });

            });
        });

        // This optional function html-encodes messages for display in the page.
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }
    </script>
}


step 8: Now run the application i.e the chat view page.

No comments:

Post a Comment