Skip to content

QuickStart Persistent Connections

davidfowl edited this page Jun 25, 2012 · 18 revisions

QuickStart (Persistent Connections)

This quickstart was designed to get you up and running quickly with a working SignalR sample using a PersistentConnection. 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 the derives from PersistentConnection:

    using System.Threading.Tasks;
    using SignalR;
    
    public class MyConnection : PersistentConnection 
    {
        protected override Task OnReceivedAsync(IRequest request, string connectionId, string data) 
        {
            // Broadcast data to all clients
            return Connection.Broadcast(data);
        }
    }

Setup Routing

Make a route for your connection:

Global.asax

    using System;
    using System.Web.Routing;
    using SignalR;

    public class Global : System.Web.HttpApplication 
    {
        protected void Application_Start(object sender, EventArgs e) 
        {
            RouteTable.Routes.MapConnection<MyConnection>("echo", "echo/{*operation}");
        }
    }

If you are setting up other routes, the SignalR mapping needs to be done before the other ones.

Client

Javascript + HTML

    <script src="http://code.jquery.com/jquery-1.7.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.signalR-0.5.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(function () {
        var connection = $.connection('/echo');

        connection.received(function (data) {
            $('#messages').append('<li>' + data + '</li>');
        });
        
        connection.start();
        
        $("#broadcast").click(function () {
            connection.send($('#msg').val());
        });
    });
    </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 connection = new Connection("http://localhost/mysite/echo");

        // Print the message when it comes in
        connection.Received += data => Console.WriteLine(message);

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

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

Clone this wiki locally