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 Microsoft.AspNet.SignalR

Server

Create a class that derives from PersistentConnection:

    using System.Threading.Tasks;
    using Microsoft.AspNet.SignalR;

    public class MyConnection : PersistentConnection 
    {
        protected override Task OnReceived(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;

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

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-1.1.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().done(function() { 
            $("#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

If you want to use the .NET client, then install the package.

Install-Package Microsoft.AspNet.SignalR.Client -pre
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(data);

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

        string line = null;
        while((line = Console.ReadLine()) != null)
        {
            // Send a message to the server
            connection.Send(line).Wait();
        }
    }
}
posted @ 2015-12-20 15:25  applekingghfhfhbr  阅读(148)  评论(0编辑  收藏  举报