2016-07-09 55 views
0

私はSignalRを初めて使用しています。私はこれまでSignalRを使用して特定のクライアントと通信する方法は?

EmployeeHub.cs

using Microsoft.AspNet.SignalR; 
using Microsoft.AspNet.SignalR.Hubs; 

namespace WebApplication1 
{ 
    public class EmployeeHub : Hub 
    { 
     [HubMethodName("NotifyClients")] 
     public static void NotifyCurrentEmployeeInformationToAllClients(string connectionID) 
     { 
      IHubContext context = GlobalHost.ConnectionManager.GetHubContext<EmployeeHub>(); 

      // update the specific connected client   
      context.Clients.Client(connectionID).updatedClients(); 
     } 
    } 
} 

HomeController.cs

using System.Collections.Generic; 
using System.Data.Entity; 
using System.Linq; 
using System.Web.Mvc; 
using WebApplication1.Models; 

namespace WebApplication1.Controllers 
{ 
    public class HomeController : Controller 
    { 
     List<Employee> empList; 

     //Fetch Employee Records 
     public ActionResult Index() 
     { 
      return View(); 
     } 
     [HttpGet] 
     public ActionResult GetAllEmployeeRecords() 
     { 
      using (var context = new EmployeeContext()) 
      { 
       empList = context 
       .Employees 
       .ToList(); 
      }   
      return PartialView("_EmployeeList", empList); 
     } 


     //Insert Employee Record 
     public ActionResult Insert() 
     { 
      return View(); 
     } 
     [HttpPost]   
     public ActionResult Insert(DataPacket dataPacket) 
     { 
      if (ModelState.IsValid) 
      { 
       //Insert into Employee table 
       using (var context = new EmployeeContext()) 
       { 
        context.Employees.Add(dataPacket.Employee); 
        context.SaveChanges(); 
       } 
      } 

      //Once the record is inserted , then notify(Clients) 
      EmployeeHub.NotifyCurrentEmployeeInformationToAllClients(dataPacket.ConnectionID); 
      return RedirectToAction("Index"); 
     }  
} 

データパケットをやっていることである私はここで、特定のクライアントに

を通信する必要があります。 CS

public class Employee 
    { 
     [Key] 
     public int EmployeeID { get; set; } 
     public string EmployeeName { get; set; } 
     public string EmailAdress { get; set; } 
     public string MobileNumber { get; set; }  
    } 

    public class DataPacket 
    { 
     public Employee Employee { get; set; } 
     public string ConnectionID { get; set; } 
    } 

、最終的には私のIndex.cshtml

@model IList<WebApplication1.Models.Employee> 
@{ 
    ViewBag.Title = "Index"; 
} 
<link href="~/Content/bootstrap/css/bootstrap.min.css" rel="stylesheet" /> 

<div>  
     <h1 style="color: green">CRUD using SignalR,MVC and Entity Framework</h1> 
     <table border="1">    
      ................................ 
     ................................ 
     </table> 
    <br /><br />  
     <div id="dataTable"></div> 
    </div> 

@section JavaScript{ 
    <script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script> 
    <script src="/signalr/hubs"></script> 
    <script type="text/javascript"> 

     $(function() { 
      // Create a proxy to signalr hub on web server. It reference the hub. 
      var notificationFromHub = $.connection.employeeHub; 

      // Connect to signalr hub 
      $.connection.hub.start().done(function() { 
       FetchEmployees(); 
      }); 

      // Notify to client with the recent updates 
      notificationFromHub.client.updatedClients = function() { 
       FetchEmployees(); 
      }; 
     }); 

     function FetchEmployees() { 
      var model = $('#dataTable'); 
      $.ajax({ 
       url: '/home/GetAllEmployeeRecords', 
       contentType: 'application/html ; charset:utf-8', 
       type: 'GET', 
       dataType: 'html' 
      }) 
       .success(function (result) { model.empty().append(result); })    
     } 

     // Insert Employee Record 
     function InsertEmployee() 
     { 


        var employee = { 
         EmployeeID: $('#txtEmployeeId').val(), 
         EmployeeName: $('#txtEmployeeName').val(), 
         EmailAdress: $('#txtEmail').val(), 
         MobileNumber: $('#txtMobile').val(),      
        }; 

        var dataPacket = { 
         Employee: employee, 
         ConnectionID: GenerateRandomNumbers() 
        } 

        $.ajax({ 
        url: '/home/Insert', 
        type: 'POST', 
        data: JSON.stringify(dataPacket), 
        contentType: "application/json;charset=utf-8", 
        success: function (data) { 
         alert('Employee added Successfully');      
        }, 
        error: function() { 
         alert('Employee not Added'); 
        } 
       }); 
     }   

     //Generate RandomNumbers 
     function GenerateRandomNumbers() { 
      var min = 1; 
      var max = 10; 
      return Math.floor(Math.random() * (max - min + 1) + min); 
     } 
    </script> 
} 

私はテスト目的のためのクライアントIDを生成するための乱数を用いた本でています。問題は、レコードがデータベースに追加されますが、ページがロードされるまで、SignalRからクライアントへの通知が行われていないことです。

など。これは、「新しい従業員の追加」ボタンをクリックしたときの状況です。

enter image description here

私は

enter image description here

のようなページの更新を行う場合にのみ、データが表に反映されます私はまたthis SO Q/Aに参照されているが、私は、私は何かが足りないと思います。

私は行方不明です。助けてください。

ありがとうございます。

答えて

1

SignalRのConnectionIdは、特定の接続先クライアントに固有の番号です。したがって、ConnectionID: GenerateRandomNumbers()は、クライアントが接続されている接続IDと同じではありません。

特定のクライアント接続ID(specified here)を取得するには、最初のハブ接続のdone()メソッドからconnectionIDを取得し、スクリプトにグローバル変数として格納する必要があります。

などです。

var connectionId = null; 

$(function() { 
//omitted code 
    // Connect to signalr hub 
    $.connection.hub.start().done(function() { 

     connectionId = $.connection.hub.id; 
     FetchEmployees(); 
    }); 
}); 

次に、aJaxコールで、乱数の代わりに実際のハブ接続IDを指定します。

最後にそれを完成させるために、再接続や切断などを検出する方法も提供します。さらに、変更または切断された場合の接続IDの更新をクリアするためのガイドです。

関連する問題