如何使用 SignalR 与特定客户端通信?
How to communicate to specific client using 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");
}
}
DataPacket.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 到客户端的通知。
例如这是我点击 "Add New Employee" 按钮时的情况。
当我像
这样刷新页面时,只有数据会反映在 table 中
我也提到了 ,但我想我遗漏了一些东西。
我缺少什么?
在 SignalR 中,ConnectionId
是特定连接客户端的特定号码。因此,您的 ConnectionID: GenerateRandomNumbers()
将与您的客户端连接的连接 ID 不同。
要获取特定的客户端连接 ID (specified here),您应该从初始 Hub 连接的 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 已更改或断开连接的情况下更新\清除连接 ID。
我是 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");
}
}
DataPacket.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 到客户端的通知。
例如这是我点击 "Add New Employee" 按钮时的情况。
当我像
这样刷新页面时,只有数据会反映在 table 中我也提到了
我缺少什么?
在 SignalR 中,ConnectionId
是特定连接客户端的特定号码。因此,您的 ConnectionID: GenerateRandomNumbers()
将与您的客户端连接的连接 ID 不同。
要获取特定的客户端连接 ID (specified here),您应该从初始 Hub 连接的 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 已更改或断开连接的情况下更新\清除连接 ID。