Share via


SignalR: Very Simple Example

Introduction

You can download the code here.

This is a very simple example of how we can use SignalR, based on the Microsoft Virtual Academy course "Building apps with ASP.NET 4.5".  It can be used as a guide for building a more complex web app. This solution requires NuGet packages to be downloaded. Visual Studio will download the necessary packages automatically. This solution is designed for Visual Studio 2012

Description

This application displays a div shape that the users can drag. The position of the shape in all other browsers will then be updated to match the position of the dragged shape*.*

As the server component, this web page contains a C# implementation of the SignalR Hub class. As the client component, it has an HTML page using JQuery .

These concepts are associated with applications in real-time gaming and other simulation applications.

http://code.msdn.microsoft.com/site/view/file/94985/1/2013-08-27_0126.png

Index.html

HTML

01.<!DOCTYPE html> 02.<html xmlns="http://www.w3.org/1999/xhtml"> 03.<head> 04.    <title>SignalR Example</title> 05.       06.        #shape { 07.            width: 100px; 08.            height: 100px; 09.            background-color: red; 10.            cursor:move; 11.        } 12.  13.         #count { 14.             font-size:60px; 15.             color:lightGray; 16.             float:right; 17.         } 18.      19.</head> 20.<body> 21.   22.    <div id="count">0</div> 23.    <div id="shape"></div> 24.  25.    <script src="Scripts/jquery-1.6.4.js"></script> 26.    <script src="Scripts/jquery-ui-1.10.3.js"></script> 27.    <script src="Scripts/jquery.signalR-1.1.3.js"></script> 28.    <script src="/signalr/hubs"></script> <!--this is for automatically  29.generate a javascript proxy class for our server class--> 30.    <script> 31.  32.        $(function () { 33.  34.            var hub = $.connection.moveShape, //set hub with the server side class 35.               $shape = $("#shape"); 36.  37.  38.  39.            hub.client.usersConnected = function (numUsers) { //this instanciate the  40.usersConnected function receiving the numUsers parameter which is the number of users connected 41.               $("#count").text(numUsers); //show the number of users connected inside a div 42.            }; 43.  44.  45.             46.  47.            hub.client.shapeMoved = function (x, y) { //this instanciate the shapeMoved function  48.receiving x, y  49.                $shape.css({ left: x, top: y }); //this moves the shape in the clients to  50.the coords x, y  51.            }; 52.  53.            $.connection.hub.start().done(function () {//when the connection is ready,  54.we going to make the shape draggable 55.                $shape.draggable({ 56.                    drag: function () { //when the user drag the shape, we going to  57.send to the server the x, y values 58.                        hub.server.moveShape(this.offsetLeft, this.offsetTop || 0); 59.                    } 60.                }); 61.            }); 62.        }); 63.  64.    </script> 65.</body> 66.</html>

 

MoveShapeHub.cs

 

C#

01.using Microsoft.AspNet.SignalR; 02.using Microsoft.AspNet.SignalR.Hubs; 03.using System; 04.using System.Collections.Generic; 05.using System.Linq; 06.using System.Threading.Tasks; 07.using System.Web; 08.  09.namespace SignalR.MoveShape 10.{ 11.      12.    public static class UserHandler //this static class is to store the number of  13.users conected at the same time 14.    { 15.        public static HashSet<string> ConnectedIds = new HashSet<string>(); 16.    } 17.  18.    [HubName("moveShape")]   //this is for use a name to use in the client 19.    public class MoveShapeHub : Hub 20.    { 21.        public void moveShape(int x, int y) // this method will be called from  22.the client, when the user drag/move the shape 23.        { 24.              25.            Clients.Others.shapeMoved(x, y); // this method will send the coord x, y  26.to the other users but the user draging the shape 27.            28.        } 29.  30.        public override Task OnConnected() //override OnConnect, OnReconnected and OnDisconnected  31.to know if a user is connected or disconnected 32.        { 33.            UserHandler.ConnectedIds.Add(Context.ConnectionId); //add a connection id to the list 34.            Clients.All.usersConnected(UserHandler.ConnectedIds.Count()); //this will send to ALL the clients  35.the number of users connected 36.            return base.OnConnected(); 37.        } 38.  39.        public override Task OnReconnected() 40.        { 41.            UserHandler.ConnectedIds.Add(Context.ConnectionId); 42.            Clients.All.usersConnected(UserHandler.ConnectedIds.Count()); 43.            return base.OnConnected(); 44.        } 45.  46.        public override Task OnDisconnected() 47.        { 48.            UserHandler.ConnectedIds.Remove(Context.ConnectionId); 49.            Clients.All.usersConnected(UserHandler.ConnectedIds.Count()); 50.            return base.OnDisconnected(); 51.        } 52.  53.  54.          55.    } 56.}

 

 

Globa.asax.cs

 

C#

01.using System; 02.using System.Collections.Generic; 03.using System.Linq; 04.using System.Web; 05.using System.Web.Routing; 06.using System.Web.Security; 07.using System.Web.SessionState; 08.  09.namespace SignalR 10.{ 11.    public class Global : System.Web.HttpApplication 12.    { 13.  14.        public void Application_Start() 15.        { 16.            // Register the default hubs route: ~/signalr 17.            RouteTable.Routes.MapHubs(); 18.        } 19.  20.        protected void Session_Start(object sender, EventArgs e) 21.        { 22.  23.        } 24.  25.        protected void Application_BeginRequest(object sender, EventArgs e) 26.        { 27.  28.        } 29.  30.        protected void Application_AuthenticateRequest(object sender, EventArgs e) 31.        { 32.  33.        } 34.  35.        protected void Application_Error(object sender, EventArgs e) 36.        { 37.  38.        } 39.  40.        protected void Session_End(object sender, EventArgs e) 41.        { 42.  43.        } 44.  45.        protected void Application_End(object sender, EventArgs e) 46.        { 47.  48.        } 49.    } 50.}

 

Return to Top

Source Code Files

  • Global.asax - The global application class is used to register the route to the autogenerated hubs proxy.
  • index.html - The client application, written using JavaScript and the JQuery library.
  • MoveShapeHub.cs - The server application, written as an implementation of a SignalR hub.

More Information

Other Languages

This article is also available the following languages: