Building A Private Chat Application Using SignalR (2024)

Introduction

Here I will demonstrate an application to chat privately using SignalR. Before that, we need to know first what SignalR is! SignalR is an open and free library that can integrate real-time functionality into your web applications. Real-time means having your server respond as quickly as possible to the client as and when a request is made. There is a hell of a lot of areas where SignalR can come in handy to make your application handier and more integrated, and more responsive to the end user as well.

For instance, we have a requirement to show the user uploading a file and the percentage of that file that has been uploaded on the server. Or I had come across a scenario where we had to show the end user who would upload a CSV file with the 'n' number of rows and process each row for some validations. End users would wonder what would happen in the back end. So, wouldn't it be great if we could show him how many rows have been processed and how many are left out? Similar to a progress window.

Here comes the SignalR magic! Most of us think SignalR would help make chat applications, but NO! It has much more than chat! I don't think the makers of SignalR would have a thought in mind to make a chat application out of it! :P Much of a story now! Let's get into a bit of theory!

Theory

We will look into a simple image below, and from that image, we will try to gain some knowledge of the flow.

Building A Private Chat Application Using SignalR (1)

Nowadays, every application requires a load of server response in real time to sustain in the market, as user expectations have risen higher. Remote Procedure Calls (RPC) are the concept in the SignalR internally. SignalR provides an API that helps make the RPC between the server and the client. From the client side, server-side functions are called using JavaScript once the connection to the server is set. The SignalR API also helps create connections and manage them when required. In simple terms, SignalR provides a connection between server and client, letting the server call the functions on the client sideand, from the client side, calling the server side.

SignalR starts with HTTP and then to a WebSocket if the connection is available. That somehow is called "Server-Push". From Wiki, "WebSocket is a protocol providing full-duplex communication channels over a single TCP connection." An advantage of using WebSocket is both client and server applications can use it. WebSocket is considered the most efficient and consistent communication medium as it can properly manage server memory and, being a full duplex communication, has low latency. These are the considerations made with SignalR, which make it more efficient. The SignalR decides the transport based on the browser.i.e., if the browsers support the kind of transport required by the SignalR, we will discuss the kinds of transport next:

HTMLTransports

  • WebSockets-as we have already discussed. This transport is considered persistent, creating a two-way connection between the client and server.
  • Server-Sent events-also called Event Sources, are supported by all browsers.

Comet Transports

Comet is usually a web application model in which a long-held HTTP request allows the server to post data to a client (browser).

  • Forever frame- This is supported by Internet Explorer only. Creates a hidden frame making a request to the endpoint on the server. The server keeps pinging the client or sending the script to the client, thus providing a one-way connection, creating a new connection on every request.
  • Ajax Polling- This is long polling, which is never persistent. This polls the request and waits until and unless the server receives the response. This introduces latency, and the connection resets.

Practical

We will be creating a chat application to explain the flow of SignalR. We install the SignalR, create a hub to which the client will interact, calling the server methods, and in return, the server responds and interacts with the client. You can directly add a new project in VS for the SignalR or create an MVC project and install the SignalR package/libraries from the Nuget.

PM > Install-Package Microsoft.AspNet.SignalR

This downloads all the dependencies required for the SignalR.

Building A Private Chat Application Using SignalR (2)

After the successful installation, the above dll's or packages are installed into your project. There will be a class file that needs to be added to the root of your project, which would look like this,

usingOwin;usingMicrosoft.Owin;[assembly:OwinStartup(typeof(SignalRChat.Startup))]namespaceSignalRChat{publicclassStartup{publicvoidConfiguration(IAppBuilderapp){//Anyconnectionorhubwireupandconfigurationshouldgohereapp.MapSignalR();}}}

This is an OWIN-based application. The OWIN attribute specifies the property type, specifies the project's startup and the configuration method, and sets up the start-upmapping for the App. Every OWIN application will have a startup.cs class, where the component for the applicatstart-upeline is added. Another two script files will be added as we install the packages for SignalR.

Building A Private Chat Application Using SignalR (3)

These script files must be loaded onto the .cshtml page to activate the SignalR. Let's look into the code immediately; We must add a new hub class inside a Hub folder. Let's name that LetsChatHub.cs, which would look like this,

Building A Private Chat Application Using SignalR (4)

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingMicrosoft.AspNet.SignalR;namespaceLetsChatApplication.Hubs{publicclassLetsChatHub:Hub{publicvoidSend(stringname,stringmessage,stringconnId){Clients.Client(connId).appendNewMessage(name,message);}}}

The above send method accepts the parameters, name (which you would give once you navigate onto the URL), and message (which the user would be sent from the UI). The other parameter is connId, which would help us have a private chat and not send it to every user who navigates to the site if you want every user to receive and send the messages who navigate to the URL. To allow every user access, the code you change as below,

namespaceLetsChatApplication.Hubs{publicclassLetsChatHub:Hub{publicvoidSend(stringname,stringmessage){Clients.All.appendNewMessage(name,message);}}}

The Send method is requested from the client with the parameters after the connection is set on the client side, and once the server receives the request, it processes and sends back the response to the client using the appendNewMessage. This appendNewMessage method is added on the client side to receive the response and display it on the UI to the client. The client-side code would look like below: you need to add a controller; let's suppose: "LetsChat" with an action "LetsChat" and add a view to that with the below code to it.

@{ViewBag.Title="LetsChat";}<h2>LetsChat</h2><linkhref="~/Content/sweetalert.css"rel="stylesheet"/><divclass="form-groupcol-xl-12"><labelclass="control-label">YourconnectionId</label><br/><inputtype="text"class="col-lg-12text-primary"id="frndConnId"placeholder="Pasteyourfriend'sconnectionId"/><br/><br/><labelclass="control-label">YourMessage</label><br/><textareatype="text"class="col-lg-10text-primary"id="message"></textarea><inputtype="button"class="btnbtn-primary"id="sendmessage"value="Send"/><br/><br/><imgsrc="~/Content/smile.jpg"width="20"height="20"id="smile"style="cursor:pointer"/><imgsrc="~/Content/uff.jpg"width="20"height="20"id="ufff"style="cursor:pointer"/><divclass="containerchatArea"><inputtype="hidden"id="displayname"/><ulid="discussion"></ul></div></div><br/><inputtype="hidden"id="connId"/><!--ReferencetheautogeneratedSignalRhubscript.-->@sectionscripts{<scriptsrc="~/Scripts/jquery-1.10.2.min.js"></script><scriptsrc="~/Content/sweetalert.min.js"></script><scriptsrc="~/Scripts/jquery.signalR-2.2.0.min.js"></script><scriptsrc="~/signalr/hubs"></script><script>//varuserName="";//varsessionVal='';$(function(){//Referencetheauto-generatedproxyforthehub.varchat=$.connection.letsChatHub;debugger;//Createafunctionthatthehubcancallbacktodisplaymessages.chat.client.addNewMessageToPage=function(name,message){//Addthemessagetothepage.$('#discussion').append('<li><strong>'+htmlEncode(name)+'</strong>:'+htmlEncode(message)+'</li>');};//Gettheusernameandstoreittoprependtomessages.swal({title:"LetsChat!",text:"<spanstyle='color:#f8bb86;font-weight:700;'>Enteryourname:</span>",type:"input",html:true,showCancelButton:true,closeOnConfirm:true,animation:"slide-from-top",inputPlaceholder:"YourName"},function(inputValue){userName=inputValue;if(inputValue===false)returnfalse;if(inputValue===""){swal.showInputError("Youneedtotypeyourname!");returnfalse;}$('#displayname').val(inputValue);});//Setinitialfocustomessageinputbox.$('#message').focus();$('#message').keypress(function(e){if(e.which==13){//Enterkeypressed$('#sendmessage').trigger('click');//Triggersearchbuttonclickevent}});$("#smile").click(function(){});//Starttheconnection.$.connection.hub.start().done(function(){$('#sendmessage').click(function(){//CalltheSendmethodonthehub.varconnId=$("#connId").val();varfrndConnId=$("#frndConnId").val();varfinalConnId=frndConnId==""?$.connection.hub.id:frndConnId;chat.server.send($('#displayname').val(),$('#message').val(),finalConnId);$("#connId").val($.connection.hub.id);if(frndConnId==""){swal("YouconnectionId",$.connection.hub.id,"success");}//Cleartextboxandresetfocusfornextcomment.$('#discussion').append('<li><strong>'+htmlEncode($('#displayname').val())+'</strong>:'+htmlEncode($('#message').val())+'</li>');$('#message').val('').focus();});});});//Thisoptionalfunctionhtml-encodesmessagesfordisplayinthepage.functionhtmlEncode(value){varencodedValue=$('<div/>').text(value).html();returnencodedValue;}</script>}

We have a normal UI to add your message and send button to call the server methods. Let's understand the code above part by part.

varchat=$.connection.letsChatHub;

Here, we set the connection to the Hub class. As you can notice, letsChatHub is the same hub class file name we added to set up the server. The convention is as follows: the methods' initial or the class name starts in lowercase. From here, we use chat to access the Send method.

$.connection.hub.start().done(function(){$('#sendmessage').click(function(){//CallstheSendmethodonthehub.chat.server.send($('#displayname').val(),$('#message').val(),finalConnId);

chat.server.send is self-explanatory; it sets the chat connection to call the server Send method once the connection is set and started.

chat.client.appendNewMessage=function(name,message){//}

This is called when the Server receives the request and calls back the method on the client side.

How would the sample work?

The sample provided for download will be having few instructions to follow,

  • When you navigate to the LetsChat/LetsChat route, an alert will pop up asking you for the name with which you would like to chat. Sweet Alert !!
    Building A Private Chat Application Using SignalR (5)
  • Once you enter the name, you see a textbox that asks you for "Your friend's connection Id", but since you are starting the chat, you send a message, and another pop-up comes up with your connection ID, which you need to share with your friends to share your message. Remember, only those with your ID and who use it while chatting can see and send messages to you.
    Building A Private Chat Application Using SignalR (6)
  • When your friend navigates, he ought to generate his connection ID and share it to set up your connection completely. Thus, you need to have the connID to whom you will send it and vice-versa with your friend. Then chat!! :)
    Building A Private Chat Application Using SignalR (7)

If you want to send messages to all and make that common, use the Clients. All code snippets to send. Another interesting thing that was figured out is the use of @section scripts{}, which lets the Signal R scripts render and active on your page, and also, using the @section scripts also provides your code a good outlook.

Share and Send files using SignalR

Ooops!! A nice question, right? Ideally, it is not advised; rather, I would not recommend sending or sharing files using Signal R. There is always a better way to accomplish that. The idea would be to use API; you can have an upload area and use SignalR to show the progress, and once the upload completes, update the user regarding the completion and generate a download link on the UI for the users to download and view the file. This is not always the best idea, but it is just another one. :)

Conclusion

This is just a simple Chat application you can use to chat with your friends if you host on Azure or any other domain. But again, SignalR is not just this much. There are a lot of other effective uses of SignalR. I will be sharing more utility of SignalR in future articles.

References

Read more articles on SignalR,

  • Adding Real-Time Functionality With SignalR
  • ASP.NET SignalR: FAQs on SignalR Script Exceptions
Building A Private Chat Application Using SignalR (2024)

FAQs

Is SignalR good for chat? ›

Using SignalR, you can write server-side code that pushes content to connected clients instantly. SignalR handles connection management automatically, and lets you broadcast messages to all connected clients simultaneously, like a chat room.

What are the disadvantages of SignalR? ›

SignalR does not offer any data integrity guarantees, has a single-region design that affects UX performance and can lead to latency, and supports only three client SDKs.

How do I set up a private chat room? ›

On your Android
  1. Open the Chat app .
  2. At the bottom, tap Rooms .
  3. Tap Add .
  4. Tap Create room.
  5. Enter a name and then tap Done .
  6. Tap Add people & bots.
  7. Enter names of people, email addresses, and bots, or select from the suggestions. ...
  8. Tap Done .

How do I make my own chat server? ›

Creating a Chat Server Using Java
  1. Introduction: Creating a Chat Server Using Java. ...
  2. Step 1: Setup a ServerSocket in the Server Class. ...
  3. Step 2: Create a Socket in the Login Class. ...
  4. Step 3: Create a Loop to Continuously Accept Clients. ...
  5. Step 4: Create the Client Threads. ...
  6. Step 5: Create the Server Thread.

Is SignalR obsolete? ›

ASP.NET SignalR: A library for ASP.NET developers. Note that this version is largely outdated (only critical bugs are being fixed, but no new features are being added).

Is SignalR better than WebSocket? ›

For pure WebSocket functionality, choose WebSocket, but for a comprehensive . NET solution with additional features and fallback options, SignalR is the way to go.

Does anyone still use chat rooms? ›

Conclusion. In conclusion, while chat rooms may not be as prevalent as they once were, they still exist and serve a purpose in certain domains. In the IT sector, chat rooms offer a platform for real-time collaboration, knowledge sharing, and problem-solving among professionals.

How do you make a private chat bot? ›

How to make a chatbot from scratch in 8 steps
  1. Step 1: Give your chatbot a purpose. ...
  2. Step 2: Decide where you want it to appear. ...
  3. Step 3: Choose the chatbot platform. ...
  4. Step 4: Design the chatbot conversation in a chatbot editor. ...
  5. Step 5: Test your chatbot. ...
  6. Step 6: Train your chatbots. ...
  7. Step 7: Collect feedback from users.
Jun 25, 2024

What is a secret chat room? ›

Secret Chat uses end-to-end encryption which offers greater levels of privacy and bolsters security of user information. All messages are encrypted with a key held only by the participants of the chat so no third parties can access secret chat content without accessing the device itself.

How do I Create a personal chat app? ›

Here is a step-by-step guide for building your own chat and messaging app.
  1. Step 1: Determine the Scope of Your Messaging App. ...
  2. Step 2: Decide Which Platform to Use. ...
  3. Step 3: Build Your User Interface. ...
  4. Step 4: Build Your Application's Backend. ...
  5. Step 5: Integrate Third-Party APIs. ...
  6. Step 6: Test Your App. ...
  7. Step 7: Launch Your App.
May 4, 2023

How to make a chat app without coding? ›

How to make a Chat app with AppsGeyser builder in 3 steps
  1. App Name: Give your chat app a unique name.
  2. Description: Write a brief description of your app.
  3. Icon: Choose or upload an icon for your app, customize the chat settings according to your preferences.

What is the architecture of a chat system? ›

Chat app architecture is the overall design and structure of a chat application. It encompasses the front-end and back-end components and the interactions between them that make it possible for users to send and receive messages in real time.

What is SignalR good for? ›

SignalR enables real-time communication through persistent connections between the client and the server. This differs from the traditional request-response model where the client must initiate a request to receive data. With SignalR, the server can send data to the client whenever it needs to, and vice versa.

Is Signal good for group chat? ›

A Signal group is built on top of the private group system technology. The Signal service has no record of your group memberships, group titles, group avatars, or group attributes.

Which app is better for chat? ›

My Top Picks
AppAvailabilityMain Disadvantage
WhatsAppiOS Android MacOSBoth parties must have the app installed
Facebook MessengerAndroid iOS Windows 10 MacOS (named Messenger for Mac)Includes annoying adverts
LineiOS Android MacOS WindowsHardly known outside of East Asia
SnapchatiOS AndroidOnly available on mobile devices
6 more rows

References

Top Articles
How To Season A Beef Roast
How To Season Ground Beef For Pizza Topping
Ohio Houses With Land for Sale - 1,591 Properties
Jefferey Dahmer Autopsy Photos
Ingles Weekly Ad Lilburn Ga
Wal-Mart 140 Supercenter Products
Tlc Africa Deaths 2021
PGA of America leaving Palm Beach Gardens for Frisco, Texas
Myunlb
Missing 2023 Showtimes Near Lucas Cinemas Albertville
Clairememory Scam
Craigslist Greenville Craigslist
Www.paystubportal.com/7-11 Login
How do you like playing as an antagonist? - Goonstation Forums
“In my day, you were butch or you were femme”
Baywatch 2017 123Movies
Letter F Logos - 178+ Best Letter F Logo Ideas. Free Letter F Logo Maker. | 99designs
623-250-6295
Why Is 365 Market Troy Mi On My Bank Statement
The Pretty Kitty Tanglewood
Bernie Platt, former Cherry Hill mayor and funeral home magnate, has died at 90
Contracts for May 28, 2020
Evil Dead Rise Showtimes Near Pelican Cinemas
Bethel Eportal
Baldur's Gate 3: Should You Obey Vlaakith?
When Does Subway Open And Close
Wiseloan Login
Devotion Showtimes Near Regency Buenaventura 6
JVID Rina sauce set1
Star Wars Armada Wikia
Waters Funeral Home Vandalia Obituaries
Valley Craigslist
Babydepot Registry
Diggy Battlefield Of Gods
Ridge Culver Wegmans Pharmacy
Minecraft Jar Google Drive
Tendermeetup Login
The Legacy 3: The Tree of Might – Walkthrough
How to Destroy Rule 34
How To Get Soul Reaper Knife In Critical Legends
Captain Billy's Whiz Bang, Vol 1, No. 11, August, 1920&#10;America's Magazine of Wit, Humor and Filosophy
Сталь aisi 310s российский аналог
Restored Republic June 6 2023
Hazel Moore Boobpedia
Craigslist Food And Beverage Jobs Chicago
Here's Everything You Need to Know About Baby Ariel
Ghareeb Nawaz Texas Menu
Expendables 4 Showtimes Near Malco Tupelo Commons Cinema Grill
Love Words Starting with P (With Definition)
Big Brother 23: Wiki, Vote, Cast, Release Date, Contestants, Winner, Elimination
Google Flights Missoula
Latest Posts
Article information

Author: Foster Heidenreich CPA

Last Updated:

Views: 6042

Rating: 4.6 / 5 (56 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Foster Heidenreich CPA

Birthday: 1995-01-14

Address: 55021 Usha Garden, North Larisa, DE 19209

Phone: +6812240846623

Job: Corporate Healthcare Strategist

Hobby: Singing, Listening to music, Rafting, LARPing, Gardening, Quilting, Rappelling

Introduction: My name is Foster Heidenreich CPA, I am a delightful, quaint, glorious, quaint, faithful, enchanting, fine person who loves writing and wants to share my knowledge and understanding with you.