Subscribe to Sergio Tapia - Lost in the GC.        RSS Feed
-----

SignalR with MVC3 | Chat App - Build asynchronous real-time persistant connection websites.

Icon Leave Comment
This is getting my vote for Tool of The Year™ 2011.

As it's description states in their GitHub page; "Async signaling library for ASP.NET to help build real-time, multi-user interactive web applications.".

In a nutshell SignalR lets you communicate with clients on your website in real time. Imagine Comet implementation without all the fuss. Dead easy to setup, dead easy to work with, fast as holy hell. Yes - I'm excited.

I'm going to show you how to build a small chat application using SignalR in an MVC3 application.

Create > New Project.

Create a new MVC3 project anywhere on your drive. This is the easy part.

Downloading and Installing SignalR.

Using NuGet you can either download SignalR using the package console, or by using the NuGet Package Manager UI. I'll show you the latter.

Right click on your References and select the manage option.

Posted Image

Search for SignalR and add a reference to the SignalR library (the first one). NuGet will manage dependencies for you.

Posted Image

Setting up the Library.

Head on over to your _Layout.cshtml file and add the needed Javascript files. Remember: Using NuGet already packed up the javascript file neatly where they need to be.

<script src="../../Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.signalR.min.js" type="text/javascript"></script>
<script src="/signalr/hubs" type="text/javascript"></script>




Next, head on over to the root of your solution and create a class called Chat.

Posted Image

using SignalR.Hubs;

namespace SingalRTest
{
    public class Chat : Hub
    {
        public void Send(string message)
        {
            //Call the addMessage method on all clients.
            Clients.addMessage(message);
        }
    }
}


The Client Side Javascript

On the client side, we'll need to write some javascript to interact with your server side SignalR.

In your _layout.cshtml file, type in the following Javascript.

<script type="text/javascript">
    $(function () {
        // Proxy created on the fly
        var chat = $.connection.chat;

        // Declare a function on the chat hub so the server can invoke it
        chat.addMessage = function (message) {
            $('#messages').append('<li>' + message + '</li>');
        };

        $("#broadcast").click(function () {
            // Call the chat method on the server
            chat.send($('#msg').val());
        });

        // Start the connection
        $.connection.hub.start();
    });
</script>



Your _layout.cshtml file should be looking like this right now:

<html >
<head runat="server">
    <script src="../../Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery.signalR.min.js" type="text/javascript"></script>
    <script src="/signalr/hubs" type="text/javascript"></script>
</head>
<body>
    <div>
        <script type="text/javascript">
            $(function () {
                // Proxy created on the fly
                var chat = $.connection.chat;

                // Declare a function on the chat hub so the server can invoke it
                chat.addMessage = function (message) {
                    $('#messages').append('<li>' + message + '</li>');
                };

                $("#broadcast").click(function () {
                    // Call the chat method on the server
                    chat.send($('#msg').val());
                });

                // Start the connection
                $.connection.hub.start();
            });
        </script>
        <input type="text" id="msg" />
        <input type="button" id="broadcast" />
        <ul id="messages"></ul>
    </div>

    <div>@RenderBody()</div>
</body>
</html>



We're done now!

You can now type in a message, click the button to send it, and SignalR will broadcast this message out to any connected clients.

Is this fantastic or what?

What's going on behind the scenes? If you open up Firebug, you can see exactly what's going on:

Posted Image

Notice that the connection remains open, until we actually do something.

You can find the source for SignalR over on GitHub. Be sure to leave them feedback for any bugs you might find. This is a new project but a very promising one at that. Some very smart people are working on it.

Thanks for reading and stop polling your website for changes - use SignalR. :)

Related Reading:
Socket.IO - http://socket.io/
Nowjs - http://nowjs.com/

0 Comments On This Entry

 

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)

About Me

Posted Image


Bienvenidos! I'm a USA ex-pat living in Bolivia for the past 10 years. Web development is my forte with a heavy lean for usability and optimization. I'm fluent in both English and Spanish. I guest write for the popular Python website Python Central. Visit my website.

Categories