Skip to content
davidfowl edited this page May 9, 2012 · 25 revisions

QuickStart (Hubs)

This quickstart was designed to get you up and running quickly with a working SignalR sample using Hubs. For more details, See the documentation.

Setup

Go to NuGet and install the SignalR package into a WebApplication:

Install-Package SignalR

Server

Create a class that derives from Hub:

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

Client

Javascript + HTML

    <script src="Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.signalR-0.5.min.js" type="text/javascript"></script>
    <script src="/signalr/hubs" type="text/javascript"></script>
    <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())
                .done(function() {
                    console.log('Success!');
                })
                .fail(function(e) { 
                    console.warn(e); 
                });
        });
        
        // Start the connection
        $.connection.hub.start();
    });
    </script>
    
    <input type="text" id="msg" />
    <input type="button" id="broadcast" value="broadcast" />

    <ul id="messages">
    </ul>

Clone this wiki locally