Skip to content
davepermen edited this page Jul 12, 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.4.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.signalR-0.5.2.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());
        });
        
        // Start the connection
        $.connection.hub.start();
    });
    </script>
    
    <input type="text" id="msg" />
    <input type="button" id="broadcast" value="broadcast" />

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

.NET

public class Program
{
    public static void Main(string[] args)
    {
        // Connect to the service
        var hubConnection = new HubConnection("http://localhost/mysite");

        // Create a proxy to the chat service
        var chat = hubConnection.CreateProxy("chat");

        // Print the message when it comes in
        chat.On("addMessage", message => Console.WriteLine(message));

        // Start the connection
        hubConnection.Start().Wait();

        string line = null;
        while((line = Console.ReadLine()) != null)
        {
            // Send a message to the server
            chat.Invoke("Send", line).Wait();
        }
    }
}

Clone this wiki locally