Skip to content
davidfowl edited this page Nov 29, 2012 · 34 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 for WebApplication

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

Install-Package Microsoft.AspNet.SignalR -pre 

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.All.addMessage(message);
        }
    }

Client

Javascript + HTML

  <script src="http://code.jquery.com/jquery-1.8.2.min.js" type="text/javascript"></script>
  <script src="Scripts/jquery.signalR-1.0.0-alpha2.min.js" type="text/javascript"></script>
  <!--  If this is an MVC project then use the following -->
  <!--  <script src="~/signalr/hubs" 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.client.addMessage = function (message) {
              $('#messages').append('<li>' + message + '</li>');
          };

          // Start the connection
          $.connection.hub.start().done(function() {
              $("#broadcast").click(function () {
                  // Call the chat method on the server
                  chat.server.send($('#msg').val());
              });
          });
      });
  </script>
    
    <div>
      <input type="text" id="msg" />
  <input type="button" id="broadcast" value="broadcast" />

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

.NET

Setup for .NET Application

Go to NuGet and install the Microsoft.AspNet.SignalR.Client package into a ConsoleApplication:

Install-Package -pre Microsoft.AspNet.SignalR.Client
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.CreateHubProxy("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