Signal R 14th March 2019

In this blog am going to take you through step by step process to create a ChatApplication using SignalR Library. You might have come across many applications where you can join a chat room and then send messages to different people in that room. We will do the same using SignalR package. In the process of doing it we will also learn how the SignalR works.Though this blog is mainly focused on learning SignalR, it will be beneficial to know the basics.

Basics Required
  • C# programming or any other programming language
  • Familiarity with Visual Studio 2017
What we will achieve at the end of this blog
  • What is SignalR
  • How to install it
  • Issues I faced while installing and how to fix them
  • Step by step approach to create a Chat application using Visual Studio which mimics room chat(multiple users can chat)
  • Complete source code is shared on Git
  • A quick 2 min demo video
  • Step by step approach to create a Chat application using Visual Studio which mimics room chat(multiple users can chat)

So What is SignalR Ever wondered how chat applications work? How do people chat with each other (either in a group or a private chat with one person). You might be aware of client server architecture and you may get that this approach won’t work in chat room applications. So, lets take a step back and understand what is client server architecture and how it is different from chat applications In Client Server architecture, Client i.e the Browser(Chrome, Internet Explorer etc) makes a request for a particular Resource on the Web. Let’s take an eg to understand better. Suppose there is a shopping website which sells “Shoes” and “Clothes”. Lets also assume that www.abc.com/shoes is the endpoint for shoes and in in www.abc.com/clothes is the endpoint for clothes Consider there is a User called Bob and he types in www.abc.com/shoes on the browser. The request goes to the Server and the Server processes the request and returns all the shoes on their website. Bob sees all the shoes he wanted to see. Now he decides to see all clothes on abc website and therefore enters www.abc.com/clothes and this time Server shows all results of clothes to Bob. Bob is happy 😊.

requesting for shoes requesting for clothes


Now as you may be aware HTTP calls are stateless. What that means is that Server doesn’t know that it was the same User Bob who made a request to Display all Clothes and Shoes in the store .As far as Server is concerned, it just got the request from the Client and it responded by serving it. If we need the server to remember the Client, then we either need to use HTTP Cookies, maintain Server Side Sessions,hidden variable,URL-rewritring etc. Going to depth of these is out of scope of this blog. Now If you go back to eg of Bob, it was Bob/Client who was requesting the Server for details everytime and not the other way around. If you wait a second and absorb above details and give a thought about it,you can find that above approach is not a efficient way to develop any chat applications.In any chat applications,2 users (private chat) or more Users(group chat) are connected to each other and they chat. Each of the User involved in the chat , expect to see the other person’s message instantly. It’s not like User will keep on hitting (refresh/f5) to see whether the other guy part of the chat typed any message etc.This is where Push Architecture comes into picture. Push architecture means that it is the server who pushes the message to the clients (registered)/browser . So In the case of chat application, the moment user types a message, the message goes to the server and the server then broadcasts the message to all the clients. SignalR Library helps us do exactly above

So Here comes SignalR....

  • It is a ASP.NET Library
  • Helps in adding real time web functionality to applications
  • Now in my eg above, I considered a chat application. But our use case is just not limited to chat application. Actually any application where user has to keep on refreshing is a candidate for SignalR. Eg, dashboards, sports websites which shows live scores etc
  • Server pushes data to the client
  • Has wrapper functions which makes developers life easy
  • Abstracts from the different techniques to implement push data

SignalR- Connection Management

  • Manages Connections automatically
  • Broadcasts messages to the connected clients simultaneously
  • Can send messages to specific client
  • Connection between Client and Server is persistent, unlike HTTP connections which are stateless

In order to understand better, Lets take an eg. Lets assume User 1,User 2,User 3 and User 4 are all connected to a chat room .Now say User 2 types a message. Server receives it and send it all the other 3 clients simultaneously. The same is depicted in the diagram.( signalR1)

signal r

Now when I said "Push",there are various varieties of "Push" .Eg are Periodic Polling, Long Polling,ForeverFrame,SSE(Server Sent Events) ,Web Sockets In this blog, am showing the Hubs programming modal though Persistent Connections model is also available but is less popular.

What are Hubs....

  • Hubs are classes to implement push services in SignalR
  • Abstraction on top of Persistent Connection programming methodology
  • Provide a higher level Remote Procedure Call framework(What is RPC…we will see in next section)
  • Perfect for different types of messages to send between Server and client
  • No need to take care of Serialization/Deserialization etc
  • Clients property allows to access all clients connected to hub
  • Can Return simple type (eg int,string,long etc) or complex type (objects of complex type) or Task
    • Complex objects and arrays of objects are automatically serialized/deserialized to/from JSON
    • Communication between Hub on the server side and Client/Browser is JSON

RPC- What is Remote procedure call?

Above, I briefly mentioned about RPC.RPC is a distributed computing methodology. RPC is a concept which enables a computer program to execute a method or a piece of program located even in another computer on a network. In the Object oriented world, there is equivalent to it called Remote Method Invocation (RMI). For eg Java has JavaRMI.SignalR enables us to perform server to client RPCs by providing wrapper functions through APIs which abstracts the complexity of performing RPCs. i.e Server which run .NET core code can call Javascript functions running on the client’s browser.

Lets do a small egample to get a better handle of the same. I have shared the whole source code in the git repository. The git URL is Source Code Link Above source code is to create a ChatRoom for Sports. People based on the interest,can join any room they wish to and chat with people of common interest.Below are the steps to create this application. It incldues all steps i followed,right from scratch to create the project. I have also included a section called "common errors" and fixes to the errorsmay come handy if you come across same issues.

Steps:

  1. Create a ASP.Net application

  2. Choose The Application type- I select “Empty”. Give Name “SportsChatRoom”

  3. When above project is created, you wont have references for SignalR.Below is the screenshot of my references and as you can see there is no "SignalR" or related libraries

    • Now lets add Hub class (MainHub.cs).So right click the project and Click on “Add”

    • Under “Web” choose “SignalR”.Call the "Hub" class as "MainHub.cs". MainHub gets all the features by extending Hub class from "Microsoft.AspNet.SignalR.Hub" class

    • Doing above will create references for signal r library and all references related to Owin

    • It also downloads "signalR javascript" and since signalR javascript depends on jquery, it also downloads "jQuery" javascript

  4. If you want to install the SignalR from Nuget,you can run below command.(Ignore the below command if you have followed above steps and if you see all references related to SignalR (including scripts) and Owin included in your project already) Install-package Microsoft.Aspnet.SignalR

  5. SingalR servers can be self-hosted, for which it uses self-host library which is built on OWIN. OWIN stands for Open Web Interface for .Net. Every Owin Application has a Startup class where you can register services and inject modules in HTTP pipeline. Now there are quite a few number of ways to bind the startup class with the runtime environment. Below , various approaches are depicted in a diagram

  6. In the startup class, ensure that you have "app.MapSignalR()" line of code.This single line of code does the setup required for SignalR to work correctly

  7. Create the startup page
    • Create "Index.html" and add it as a “start page”.

    • Add “jQuery”,”signalR” and “signalr/hubs” javascript to the index.html’s header.

    • I also added “bootstrap.js”. Though bootstrap has nothing to do with signalR, I added it just to create a simple User Interface quickly.Below is how my index html's header looks like

  8. Once your SignalR application starts successfully,to verify if configuration and everything is related to signalr is done right, go to Chrome Dev tools (F12 on Chrome) and look for sources. If everything is correct, then you will see a "signalr" folder and a javascript file "hubs" downloaded automatically.

Common Errors Faced and Solutions:

  1. Issue 1: Incase you have "Global.asax.cs" file and you get below error
    Solution to above problem is simple.Ensure that you follow these steps
    • In the global application class, remove the call to MapHubs.
    • Right-click the solution, and select Add, New Item.... In the dialog, select Owin Startup Class. Name the new class Startup.cs (Incase you dont have one)
    • Replace the contents of Startup.cs with the following code
  2. Issue 2: Incase you get an error which says SignalR is not loaded like below
    Solution to above problem is simple.Ensure that you follow these steps
    • In the HTML file where you have included SignalR,(in this case "index.html"), ensure that signalr javascript is loaded after jquery javascript. Correct order as shown in diagram below is First, jquery-x.x.x.js, then you should have jquery.signalR-x.x.x.js and then you should have /signalr/hubs. This order is important for the page to load properly

Source Code For this app


Lets see a quick demo of the app

Demo link is shared below.In the video, I use "Chrome" and "Firefox" just to mimic 2 different users since I have hosted my application locally.(You can also test on one browser by launching them in incognito mode).In real time, it can be any number of users using any browser.

Lets understand the scenario.Assume, there are 2 people(lets call them Bob and Tim ) decide to chat on cricket and join a chat room.

1)Bob,the first User,goes to the website using Firefox and clicks on "Cricket Chat Room" and then enters the name in the popup prompted and click on "Join Room".

2)James,the other User does the same above using Chrome.

After joining room successfully,both of them can share any number of messages in the room .In the demo, you can see that when a user types in message the other gets the message instantly.If any other person joins the room, he too can see and send the messages like these 2 people.This whole scenario is demonstrated in the video.

Link to the demo

Did you like the blog or have questions, please add your comments