Contoh Sederhana Penggunaan SignalR (id-ID)

Contoh Sederhana Penggunaan SignalR (id-ID)

Pendahuluan

Melanjutkan tulisan saya sebelumnya Pengenalan SignalR, pada tulisan kali ini saya berikan contoh sederhana penggunaan singalR. Contoh ini diambil dari kursus Microsoft virtual academy "Building apps with ASP.NET 4.5". Pada tutorial ini Anda membutuhkan paket NuGet untuk mengunduh. Visual Studio akan mengunduh paket yang dibutuhkan secara otomatis. Contoh ini didesain untuk Visual Studio 2012.

Penjelasan

Aplikasi ini menampilkan sebuah obyek div yang mana pengguna bisa menggesernya. Letak obyek yang ditampilkan di semua peramban lain akan diupdate sesuai dengan posisi obyek yang digeser.

Sebagai komponen server, halaman web menerapkan kelas SignalR Hub menggunakan C#, pada sisi klien menggunakan HTML dan jQuery.

Konsep ini digunakan dalam aplikasi Game real-time dan aplikasi simulasi lainnya.

Berkas Kode Sumber

Index.html
Aplikasi klien, ditulis menggunakan JavaScript dan pustaka JQuery.
MoveShapeHub.cs
Aplikasi server, penerapan SignalR hub.
Global.asax.cs
Kelas aplikasi global, digunakan untuk mendaftarkan rute ke proxy hubs yang dibuat otomatis.

Index.html

<!DOCTYPE html>
<head>
    <title>SignalR Example</title>
       
        #shape {
            width: 100px;
            height: 100px;
            background-color: red;
            cursor:move;
        }
  
         #count {
             font-size:60px;
             color:lightGray;
             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

using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
  
namespace SignalR.MoveShape
{
      
    public static class UserHandler //this static class is to store the number of 
users conected at the same time
    {
        public static HashSet<string> ConnectedIds = new HashSet<string>();
    }
  
    [HubName("moveShape")]   //this is for use a name to use in the client
    public class MoveShapeHub : Hub
    {
        public void moveShape(int x, int y) // this method will be called from 
the client, when the user drag/move the shape
        {
              
            Clients.Others.shapeMoved(x, y); // this method will send the coord x, y 
to the other users but the user draging the shape
            
        }
  
        public override Task OnConnected() //override OnConnect, OnReconnected and OnDisconnected 
to know if a user is connected or disconnected
        {
            UserHandler.ConnectedIds.Add(Context.ConnectionId); //add a connection id to the list
            Clients.All.usersConnected(UserHandler.ConnectedIds.Count()); //this will send to ALL the clients 
the number of users connected
            return base.OnConnected();
        }
  
        public override Task OnReconnected()
        {
            UserHandler.ConnectedIds.Add(Context.ConnectionId);
            Clients.All.usersConnected(UserHandler.ConnectedIds.Count());
            return base.OnConnected();
        }
  
        public override Task OnDisconnected()
        {
            UserHandler.ConnectedIds.Remove(Context.ConnectionId);
            Clients.All.usersConnected(UserHandler.ConnectedIds.Count());
            return base.OnDisconnected();
        }
  
  
          
    }
}

Globa.asax.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Web.Security;
using System.Web.SessionState;
  
namespace SignalR
{
    public class Global : System.Web.HttpApplication
    {
  
        public void Application_Start()
        {
            // Register the default hubs route: ~/signalr
            RouteTable.Routes.MapHubs();
        }
  
        protected void Session_Start(object sender, EventArgs e)
        {
  
        }
  
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
  
        }
  
        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
  
        }
  
        protected void Application_Error(object sender, EventArgs e)
        {
  
        }
  
        protected void Session_End(object sender, EventArgs e)
        {
  
        }
  
        protected void Application_End(object sender, EventArgs e)
        {
  
        }
    }
}

Referensi

Leave a Comment
  • Please add 2 and 3 and type the answer here:
  • Post
Wiki - Revision Comment List(Revision Comment)
Wikis - Comment List
Sort by: Published Date | Most Recent | Most Useful
Posting comments is temporarily disabled until 10:00am PST on Saturday, December 14th. Thank you for your patience.
Comments
  • Richard Mueller edited Original. Comment: Replace RGB values with standard color names in HTML to restore colors

Page 1 of 1 (1 items)