Sunday, August 24, 2014

Broadcast Messages using Signalr and Asp.Net Mvc 4

Broadcast Messages using Signalr and Asp.Net Mvc 4

In this article, I’m explaining about the signalr and how to broadcast a message using the signalr.

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.
Pushing data from the server to the client (not just browser clients) has always been a tough problem. SignalR makes it dead easy and handles all the heavy lifting for you.
SignalR supports "server push" or "broadcasting" functionality. It handles connection management automatically. In classic HTTP connections for client-server communication connection is re-established for each request, but SignalR provides persistent connection between the client and the server. In SignalR the server code calls out to a client code in the browser using Remote Procedure Calls (RPC), rather than request-response model today.

Where to use:
  •         Chat room applications
  •         Real-time monitoring applications
  •         Job progress updates
  •         Real time forms


Example


Step 1

First create an empty asp.net mvc 4 application and install the signalr in it:
Go to Library Package Manager -> Package Manager Console:






Step 2

Now create a folder named “Hubs” and add a SignalR Hub Class and named it “ChatHub” like this:




And write the below code in it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;

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




Step 3

Now add another class in the Hubs folder and named it “StartUp” like this:
using Microsoft.Owin;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
[assembly: OwinStartup(typeof(SignalrMvcApp.Hubs.StartUp))]
namespace SignalrMvcApp.Hubs
{
    public class StartUp
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}



Step 4

Now add a controller named “HomeController” like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SignalrMvcApp.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

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

    }
}




Step 5

Now add a view to the project named “Index” and write the below code in it:
<html>
<head>
    <title>Signalr Sample</title>
</head>
<script src="~/Scripts/jquery-1.6.4.min.js"></script>
<script src="~/Scripts/jquery.signalR-2.1.1.min.js"></script>
<script src="~/signalr/hubs"></script>
    <script type="text/javascript">
        $(function () {

            var chat = $.connection.chatHub;

            $.connection.hub.start().done(function () {
                $('#btnSend').click(function () {
                    chat.server.send($('#name').val(), $('#txtMessage').val());
                    $('#txtMessage').val('').foucs();
                });
            });

            chat.client.broadcastMessage = function (name, message) {
                var encodedName = $('<div />').text(name).html();
                var encodedMessage = $('<div />').text(message).html();

                $('#MessageList').append('<li><strong>' + encodedName + '</strong> : &nbsp;&nbsp;' + encodedMessage + '</li>');
            };

            $('#name').val(prompt('Enter Name : ', ''));

        });
    </script>

<body>
    <div>
        <div>
            <input type="text" id="txtMessage" />
            <input type="button" value="Send" id="btnSend" />
             <input type="hidden" id="name" />
        </div>

        <div>
            <ul id="MessageList">
            </ul>
        </div>

    </div>
</body>
</html>




Now your solution explorer will look like this:



Output

Now run the application in google chrome:
First it will ask for your name:



Write a message in the textbox and click on send




Now copy the url of the application and paste it in Mozilla firefox:
It will also ask for your name:





Type a message and click on send button:




Now go to google chrome again and you will see the same message here also:



Thank you for reading this article, please put your valuable comment or any suggestion/question in the comment box.



No comments:

Post a Comment