Tags

, , ,

What is ASP.NET SignalR?

ASP.NET SignalR is a library for ASP.NET developers which helps to add real-time web functionality to their applications. Real-time web functionality is the ability to have server code push content to connected clients instantly as it becomes available, rather than having the server wait for a client to request new data.

Please read more about theory here: Introduction to SignalR

Requirements

Before we start, we have to meet a basic system requirements.

Supported server operating systems:

  • Windows Server 2012
  • Windows Server 2008 r2.
  • Windows 8
  • Windows 7
  • Windows Azure

Supported server .NET Frameworks:

  • .NET Framework 4.5
  • .NET Framework 4

Supported server IIS versions:

  • IIS8
  • IIS 7.5 and IIS 7 with extensionless URLs update. You can install this update via Web Platform Installer.

For more information please visit ASP.NET website.

1. Installing ASP.NET SignalR

For this example we will use ASP.NET MVC 4 Web Application. Before we proceed we have to install NuGet Package Manager which will help us install SignalR. Please follow the instructions here.

a) After you installed NuGet Package Manager, Open Visual Studio.
b) Create new ASP.NET MVC 4 Web application.
c) To show Package Manager Console go to View – Other Windows and select Package Manager Console. This will show you a console that we use to install SignalR.

How to show your Package Manager Console

d) To install SignalR into your project go to Package Manager Console which is now located where your Error and Output windows are (at the bottom) and use command: Install-Package Microsoft.AspNet.SignalR

SignalR install command

2. Back-end logic

ChatHub.cs

a) Select project and make new folder called Hubs.
b) Add new class to folder Hubs and name it ChatHub.cs (Select folder – Add – Class…)
c) You have to derive ChatHub class from abstract class Hub:

public class ChatHub : Hub

d) Visual Studio will inform you about error. Add SignalR reference, so Visual Studio can recognize Hub:

using Microsoft.AspNet.SignalR;

e) We have to add our method, which will send our chat message to all clients. Implement it with name and message attributes:

public void SendMessage(string name, string message)
 {
     Clients.All.AddMessage(name, message);
 }

Method is named SendMessage and takes 2 parameters from client side, which then passes to AddMesage method, which helps server sending our name and message to all users.

Final code:

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

namespace Chat.Hubs
{
    public class ChatHub : Hub
    {
        public void SendMessage(string name, string message)
        {
            Clients.All.AddMessage(name, message);
        }
    }
}

Global.asax

a) We have to implement MapHubs() method, inside of method Application_Start():

protected void Application_Start()
 {
    AreaRegistration.RegisterAllAreas();
    // Register the default hubs route: ~/signalr
    RouteTable.Routes.MapHubs();

    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    AuthConfig.RegisterAuth();
 }

which makes sure that our Hubs are routed properly.

2. Front-end logic

We will put our front-end logic to Home view Index.cshtml.

@section scripts {
    <script src="~/Scripts/jquery.signalR-1.1.2.min.js"></script>
    <script src="~/signalR/hubs"></script>
    <script>
        $(function () {
            //creating hub
            var chat = $.connection.chatHub;

            //method that is used by server to push messages to clients
            chat.client.addMessage = function (frm, message) {
                $("#messages").append("<strong>" + frm + ": </strong>" + message + "<br/>");
            };

            //when hub starts, we can send messages
            $.connection.hub.start().done(function () {
                $("#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("");
                }
                });
            });
        });
    </script>
}

<div>Your ID: @Session.SessionID</div>
<input type="text" id="txtMsg" />
<div id="messages">
</div>

This is it. All steps needed to create multi-user chat communication with SignalR.

Chat between 2 clients

Chat between 2 clients

You can download the project files here: 01Chat.rar

In Part 2, I will expand our chat application with more  functionality and database usage.

Advertisements