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
// [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)

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="">
    <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>
    <input type="text" id="theMessage" />

    <button>Send message</button>

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


    $(function () {
        var tmntHub = $.connection.tmntHub;


        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);            



Complete code:

Happy Coding!

No comments:

Post a Comment