Skip to content

QuickStart Persistent Connections

mitcht edited this page Apr 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(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.Hosting.AspNet.Routing;

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.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>

Clone this wiki locally