[Blog Post] How To Write A Real Time Chat Application In Only 5 Minutes! (Using SignalR)


chat

Hi everyone,

My two previous posts were about what I experienced in the US. I used to post my articles in english on my other web site. Now, I’ll use this web site both in English and Turkish.

I would like to introduce you “How to code a Real Time Chat Application in 5 Minutes using SignalR”.  Maybe you are thinking that it is not possible to code a real time chat application in 5 minutes. However, I will show you how to do it in 8 easy steps.

What is SignalR?

SignalR is a library for .NET to add real-time  functionality to your applications that has been developed by  and  in ASP.NET Team at Microsoft.

Technical Requirement

We’ll be using ASP.NET MVC 4 on Visual Studio 2012 with C# to develop this sample. Also, you should install ASP.NET Fall 2012 Update to use SignalR without using NuGET.

Beginning

As you may know, there is always a problem to access from Server Side to Client Side and the other way around while developing a Web Site. Moreover, there is also a problem about updating the web page in real time. When a comment is posted on Facebook, a new tweet is posted on twitter or a mail is just received, a notification is displayed in real time into our screen. You may want to develop a chat application like I’ll do.  One important thing  you should take into consideration is the difficulty that web developers encounter to reach clients whenever they would like to.

Let’s Do It

#1 Step: Create ASP.NET MVC 4 Application (Basic Project Template)

step1_ASPNET_MVC_4_Basic_Template

#2 Step: Right Click to Models, then add SignalR Hub Class and name it “ChatHub”

step2_ASPNET_MVC_4_Basic_Template_Models_SignalR_Hub_Class

Also, you can add SignalR Hub Class by right click on model to Add New Item :

step3_ASPNET_MVC_4_Basic_Template_Models_Add_New_Item_SignalR_Hub_Class

#3 Step: Coding on Server Side

step3_ASPNET_MVC_4_Basic_Template_Models_Add_New_Item_SignalR_Hub_Class_Coding

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

namespace ChatApplication.Models
{
    public class ChatHub : Hub
    {
        public void SendMessage(string from, string message)
        {
            Clients.All.AddMessage(from, message);
        }
    }
}

#4 Step: Create a Controller and name it  “Home”

step4_aspnet_mvc_basic_template_signalR_Controller_HomeController

#5 Step: Add a View and Name it “Index”

step5_aspnet_mvc_basic_template_signalR_Controller_HomeController_Add_View_Index

#6 Step: Reference Script Libraries (between head tags)

step6_aspnet_mvc_basic_template_signalR_Controller_HomeController_Add_View_Index_reference_Script_Library_SignalR_Hubstep6_aspnet_mvc_basic_template_signalR_Controller_HomeController_Add_View_Index_reference_Script_Library_SignalR_Hub_All_jQuery_Libraries

    <script src="~/Scripts/jquery-1.7.1.min.js"></script>
    <script src="~/Scripts/jquery.signalR-1.0.0-alpha1.min.js"></script>
    <script src="~/SignalR/Hubs"></script>

Besides you can use Bundle Config, If you want to.

#7 Step: Coding on Client Side

step7_aspnet_mvc_basic_template_signalR_Controller_HomeController_Add_View_Client_Side_Coding

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="~/Scripts/jquery-1.7.1.min.js"></script>
    <script src="~/Scripts/jquery.signalR-1.0.0-alpha1.min.js"></script>
    <script src="~/SignalR/Hubs"></script>
    <!-- The one Above does not exist, this will be generated by itself after the project is ready !-->
    <script type="text/javascript">
        $(function () {
            //Create Hub on Air
            var chat = $.connection.chatHub;

            //Messages
            $messages = $("#messages");

            //Client Side Method To Access From Server Side Method
            chat.client.addMessage = function (frm, msg) {
                $messages.append("<br /><b>" + frm + ":</b>" + msg);
            }

            $("#txtMsg").keypress(function (e) {
                //when enter
                if (e.which == 13) {

                    //get value of input
                    var input = $(this).val();

                    //send message to "Server Side Method"
                    chat.server.sendMessage("@Session.SessionID", input);

                    //Reset TextBox
                    $(this).val("");
                }
            });
            //Hub Starting
            $.connection.hub.start();
        });
    </script>
</head>
<body>
    <div>Your ID: @Session.SessionID</div>
    <input type="text" id="txtMsg" />
    <div id="messages">
    </div>
</body>
</html>

#8 Step: Result

Video:

As you see it, this’s so easy to develop real time chat application in 5 minutes or less. SignalR is awesome technology I have learned recently.

How happened?

First of all, What we know about SignalR is that it’s not only use for ASP.NET MVC.  In addion to that, It’s also used for the  some technologies which are Windows Phone, Windows 8, ASP.NET, ASP.NET MVC, Windows Azure, …

Regarding to the #3 Step, We create a Class inherited from “Hub” to use as “SignalR Hub”. It means that the class you are going to write  is used for SignalR. When the project  works on IIS,  The methods inside the class will be ready for comminucation between the browser and server. we use “All” keyword after “Clients” keyword and then use function name in client(JavaScript), because we would like to send a message to all clients.

At Step 7, initially, we created a hub on air. Since we name our method as “AddMessage” in ChatHub Class, we should use “chat.client.addMessage”. In the same way, we name our function as “SendMessage” in javascript  to reach server side method in ChatHub class.

I’ll give you more details about SignalR later. Please, keep checking my blog for further details.

Download

Download using this link.

More Details:

Have a nice coding!

, , , , , , , , , , , ,

  1. #1 by gkhn on January 4, 2013 - 2:29 am

    Nice Job:)

  2. #3 by pro yazılım on January 10, 2013 - 12:38 pm

    Siteni ve yazılılarını çok beğeniyor ve hep takip ediyorum benimde bu şekilde yazılar yazdığım bir bloğum var yazılarının takipçisiyim devam etmeni istiyorum.Başarılar…

  3. #4 by Nir on January 12, 2014 - 3:42 pm

    Thanks!

  4. #5 by Denver Designer Jewelry on March 29, 2015 - 9:04 pm

    Different exclusions might apply.

  1. [Incredible Blog Post] Validation Using The Data Annotation Validators in ASP.NET MVC (10 Useful/Favorite Attributes;CustomValidation, Remote, Compare, StringLength, DataType, RegularExpression, Range, Display, Required, DisplayFormat) « Mahmut Can
  2. [Blog Post(Turkish)] ASP.NET MVC İle İlgili Tüm Yazılarım (29 Yazı, 1 Yazı Dizisi ve 1 İpucu Serisi) « Mahmut Can Sozeri
  3. [Blog Post] ASP.NET MVC 5 ve SignalR ile 5 Dakika’da Chat/Mesajlaşma Uygulaması Yazmak | Mahmut Can Sozeri

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s