Skip to content
davidfowl edited this page May 13, 2012 · 9 revisions

Using SignalR Selfhost

The default SelfHost implementaion is built on HttpListener and can be hosted in any kind of application (Console, Windows Service etc).

Getting Started

To get started, install the self host package:

Install-Package SignalR.Hosting.Self

Full Sample (Console Application)

using System;
using System.Diagnostics;
using System.Threading.Tasks;

namespace SignalR.Hosting.Self.Samples
{
    class Program
    {
        static void Main(string[] args)
        {
            string url = "http://localhost:8081/";
            var server = new Server(url);
            
            // Map connections
            server.MapConnection<MyConnection>("/echo");

            // Start the server
            server.Start();

            Console.WriteLine("Server running on {0}", url);

            // Keep going until somebody hits 'x'
            while (true)
            {
                ConsoleKeyInfo ki = Console.ReadKey(true);
                if (ki.Key == ConsoleKey.X)
                {
                    break;
                }
            }
        }

        public class MyConnection : PersistentConnection
        {
            protected override Task OnConnectedAsync(IRequest request, string connectionId)
            {
                Console.WriteLine("{0} connected", connectionId);
                return base.OnConnectedAsync(request, connectionId);
            }

            protected override Task OnReceivedAsync(Hosting.IRequest request, string connectionId, string data)
            {
                return Connection.Broadcast(data);
            }

            protected override Task OnDisconnectAsync(string connectionId)
            {
                Console.WriteLine("{0} left", connectionId);
                return base.OnDisconnectAsync(connectionId);
            }
        }
    }
}

Clone this wiki locally