Thursday, September 25, 2014

SignalR in three easy steps

Step 0: Create an empty ASP.NET Web Application, get SignalR from Nuget


Step 1, create the start-up class. SignalR look for the name Startup when your app starts

using Owin;

// If you need to use other class name http://www.asp.net/aspnet/overview/owin-and-katana/owin-startup-class-detection
// [assembly: Microsoft.Owin.OwinStartup(typeof(PlaySignalR.StartMeUp))]

namespace PlaySignalR
{

    // By convention, SignalR look for Startup class name. Renaming this would cause runtime error if you don't specify OwinStartup attribute
    public class Startup
    {
        // SignalR also look for this method signature. The name Configuration could also be renamed, it's specified in attribute/web.config
        public void Configuration(Owin.IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}


Step 2, create a communication hub:

namespace PlaySignalR
{
    // Teenage Mutant Ninja Turtles Hub
    public class TmntHub : Microsoft.AspNet.SignalR.Hub
    {
        public void TellAprilONeil(string name, string message)
        {
            Clients.All.cowabungaToTurtles(name, message);
        }
    }
}


Last step, add Default.aspx, then use this:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PlaySignalR.Default" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="/Scripts/jquery-1.6.4.min.js"></script>
    <script src="/Scripts/jquery.signalR-2.1.2.js"></script>
    <script src='<%: ResolveClientUrl("~/signalr/hubs") %>'></script>
</head>
<body>
    
    <input type="text" id="theMessage" />

    <button>Send message</button>

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

</body>

<script>
    $(function () {
        var tmntHub = $.connection.tmntHub;

        tmntHub.connection.start();

        tmntHub.client.cowabungaToTurtles = function (name, message) {
            
            $('#messages').append("<p>" + name + ": " + message + "</p>");
        };

        $('button').click(function () {
            var text = $('#theMessage').val();            
            tmntHub.server.tellAprilONeil('<%: Guid.NewGuid()%>', text);            
        });
        

    });
</script>

</html>



Complete code: https://github.com/MichaelBuen/PlaySignalR


Happy Coding!

No comments:

Post a Comment