Share via


SignalR: Exemple très simple

Introduction

Vous pouvez télécharger le code

Il s'agit d'un exemple très simple de comment nous pouvons utiliser SignalR, basée sur le cours d'académie virtuelle microsoft  "Building apps with ASP.NET 4.5" . Il peut être utilisé comme un guide pour la création d'une application web plus complexe. Cette solution nécessite NuGet packages à télécharger. Visual Studio télécharge automatiquement les paquets nécessaires. Cette solution est conçue pour Visual Studio 2012.

Description

Cette application affiche une forme div que les utilisateurs peuvent faire glisser. La position de la forme dans tous les autres navigateurs sera ensuite actualisée pour correspondre à la position de la forme déplacée.

Comme le composant serveur, cette page web contient une implémentation c# de la classe SignalR Hub et comme le composant client une page HTML à l'aide de JQuery.

Cette concepts sont associés à des applications dans le jeu en temps réel et d'autres applications de simulation.

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

Index.html

HTML

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml This link is external to TechNet Wiki. It will open in a new window. "> 
<head> 
    <title>SignalR Example</title> 
        
        #shape { 
            width: 100px; 
            height: 100px; 
            background-color: #FF0000; 
            cursor:move; 
        } 
   
         #count { 
             font-size:60px; 
             color:#cccccc; 
             float:right; 
         } 
       
</head> 
<body> 
    
    <div id="count">0</div> 
    <div id="shape"></div> 
   
    <script src="Scripts/jquery-1.6.4.js"></script> 
    <script src="Scripts/jquery-ui-1.10.3.js"></script> 
    <script src="Scripts/jquery.signalR-1.1.3.js"></script> 
    <script src="/signalr/hubs"></script> <!--this is for automatically  
generate a javascript proxy class for our server class--> 
    <script> 
   
        $(function () { 
   
            var hub = $.connection.moveShape, //set hub with the server side class 
               $shape = $("#shape"); 
   
   
   
            hub.client.usersConnected = function (numUsers) { //this instanciate the  
usersConnected function receiving the numUsers parameter which is the number of users connected 
               $("#count").text(numUsers); //show the number of users connected inside a div 
           }; 
   
   
              
   
            hub.client.shapeMoved = function (x, y) { //this instanciate the shapeMoved function  
receiving x, y  
                $shape.css({ left: x, top: y }); //this moves the shape in the clients to  
the coords x, y  
            }; 
   
            $.connection.hub.start().done(function () {//when the connection is ready,  
we going to make the shape draggable 
                $shape.draggable({ 
                    drag: function () { //when the user drag the shape, we going to  
send to the server the x, y values 
                        hub.server.moveShape(this.offsetLeft, this.offsetTop || 0); 
                    } 
                }); 
            }); 
        }); 
   
    </script> 
</body> 
</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.}

fichiers des codes source

  • ​Global.asax - La classe d'application globale, utilisée pour enregistrer l'itinéraire vers leproxy de moyeux générés automatiquement.
  • index.html - L'application cliente, écrite à l'aide de JavaScript et la bibliothèque JQuery.
  • MoveShapeHub.cs - L'application serveur, écrite comme une implémentation d'un concentrateurSignalR.

Plus d'informations  http://www.asp.net/signalr http://www.microsoftvirtualacademy.com/Content/ViewContent.aspx?et=2507&m=2505&ct=15703#fbid=0iBWJyz1tez