SingalR example in mvc real time group chat

 





Introduction

ASP.NET SignalR is a library for ASP.NET developers to add real-time web functionality to their applications. Real-time web functionality is the ability to have server-side code push content to the connected clients as it happens, in real-time.


Description

SignalR is fast and scalable

Like the rest of ASP.NET, SignalR was built for high performance and is one of the fastest real-time frameworks around.

Scale out across servers with built-in support for using Redis, SQL Server, or Azure Service Bus to coordinate messages between each instance.


Open source, open protocol

SignalR is open-source on GitHub, just like the rest of .NET. In addition to the source code, the protocol specification for communication between hubs and clients is open too.


There are two sides -- One is Server Side and another one is Client Side.

The Hub in server side invokes the client side function from Hub Proxy.

Here a response is made.


Here The Hub Proxy in Client Side invokes the server side function from Hub.

Here Request Is Made.

signalR can be hosted using Open Web Interface in .NET called OWIN in signalR In another sense it can be self-hosted. It has the ability to send the contents of a server to currently connected clients.

Remote Procedure Calls (RPC)

SignalR provides an API which helps in making the call between the server and the client. The server calls the functions on the client side and the client side calls the server side. That somehow is called "Server-Push".

SignalR Transport Medium

It is integrated with ASP.NET web applications, it can be implemented by other .NET Client side Application like Windows Phone or even Windows 8/10 application.

It has four transport mediums like >>

  1. WebSocket.
  2. Server-Sent Event.
  3. ForEver Frame.
  4. Long Polling.

    SignalR initiates with HTTP and then upgrades to a WebSocket if the connection is available. An advantage of WebSocket is it can be used by both client and server applications. SignalR supports the transport based on the browser; i.e. which required transport the browser supports. Server Sent events are also called Event Source, which is not supported by only IE browser.

    A SignalR Chat Based Application using MVC in dot net





HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace RealTimeChatGroupDemo.Controllers
{
    public class HomeController : Controller
    {

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

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}


add the below NuGet packages in solutions references.








hub.js
$(function () {
    var chat = $.connection.chatHub;
    chat.client.addNewMessageToPage = function (name, message) {
        $('#discussion').append('<ul style="list-style-type:square"><li><strong style="color:red;font-style:normal;font-size:medium;text-transform:uppercase">' + htmlEncode(name) + '  ' + '<strong style="color:black;font-style:normal;font-size:medium;text-transform:lowercase">said</strong>'
            + '</strong>: ' + '<strong style="color:blue;font-style:oblique;font-size:medium">' + htmlEncode(message) + '</strong>' + '</li></ul>');
    };

    $('#displayname').val(prompt('Please enter your name:', ''));

    $('#message').focus();
    $.connection.hub.start().done(function () {
        $('#sendmessage').click(function () {
            chat.server.send($('#displayname').val(), $('#message').val());
            $('#message').val('').focus();
        });
    });
});
function htmlEncode(value) {
    var encodedValue = $('<div />').text(value).html();
    return encodedValue;
}  


add the singnalR class .




ChatHub.cs

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

namespace RealTimeChatGroupDemo
{
    public class ChatHub : Hub
    {
        
        public void Send(string name, string message)
        {
            Clients.All.addNewMessageToPage(name, message);
        }
    }
}

added the Chat.cshtml page.



@{
    ViewBag.Title = "Chat Group";
}
<fieldset>
    <legend style="color:orangered">Group Chat signalR Dot Net MVC Web Application</legend>
</fieldset>
<div class="form-group col-xl-12">
    <label style="color: blue; font-style: oblique;font-size: medium" id="label1">Write Your Message Here!</label><br />
    <textarea class="form-control" rows="4" cols="40" id="message" placeholder="Share what's in your mind..."></textarea>
    <br />
    <input type="button" class="btn btn-primary" id="sendmessage" value="Send" />
    <br />
    <br />
    <label style="color: blue;font-style:oblique;font-size:medium" id="label2">Group Chat Conversations History</label>
    <div class="container chatArea">
        <input type="hidden" id="displayname" />
        <ul id="discussion"></ul>
    </div>
</div>
@section scripts {
    <script src="~/Scripts/jquery.signalR-2.4.3.min.js"></script>
    <script src="~/signalr/hubs"></script>
    <script>

        $(function () {
            var chat = $.connection.chatHub;
            chat.client.addNewMessageToPage = function (name, message) {
                $('#discussion').append('<ul style="list-style-type:square"><li><strong style="color:green;font-style:normal;font-size:medium;text-transform:uppercase">' + htmlEncode(name) + '  ' + '<strong style="color:yellow;font-style:normal;font-size:medium;text-transform:lowercase">said</strong>'
                    + '</strong>: ' + '<strong style="color:blue;font-style:oblique;font-size:medium">' + htmlEncode(message) + '</strong>' + '</li></ul>');
            };
            $('#displayname').val(prompt('Please enter your name:', ''));
            $('#message').focus();
            $.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    chat.server.send($('#displayname').val(), $('#message').val());
                    $('#message').val('').focus();
                });
            });
        });
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }
    </script>
}   

Output below:

























DOT NET ADDA

interested in solving the problems based on technologies like Amazon AWS ,Google Cloud, Azure and Dot related technology like asp.net, C#, asp.net core API, swagger, react js,Jquery ,javascripts, bootstrap, css,html, ms sql,IIS,WPF ,WCF,Firebase,RDLC Report etc..

1 Comments

Post a Comment
Previous Post Next Post