当前位置:网站首页>Signalr can actively send data from the server to the client
Signalr can actively send data from the server to the client
2022-04-23 17:04:00 【begeneral】
scene : The server opens a in the background HttpListener Listen to third-party devices through http The real-time data of the device sent by the protocol , When the server receives the real-time data of the device , adopt SignalR Technology sends data to the front end
Let's first look at the server to add SignalR Component steps .
First of all, we should start from NuGet Up lookup SignalR Components , Install the following two components :
![]()
Right click on the current project , Add new item , find OWIN Startup class , Click Add . The code is as follows :
public void Configuration(IAppBuilder app)
{
// More about how to configure your application , Please visit https://go.microsoft.com/fwlink/?LinkID=316888
app.MapSignalR();
}
Create a new item, and then add ,SignalR Hub Class, Add SignalR Hub class for . The hub class code is as follows :
[HubName("HubDemo")]
public class HubDemo : Hub
{
private readonly HubDemoService _hubDemoService;
public static HubDemo Instance { get; } = new HubDemo(HubDemoService.Instance);
public HubDemo() : this(HubDemoService.Instance)
{
}
public HubDemo(HubDemoService hubDemoService)
{
_hubDemoService = hubDemoService;
}
public void Hello(string projectID)
{
Groups.Add(Context.ConnectionId, projectID);
_hubDemoService.Hello();
}
public void SendClient(string deviceSN)
{
_hubDemoService.SendClient(deviceSN);
}
}
Here we build a service class of hub class to complete the specific data sending task , The code of the service class is as follows :
public class HubDemoService
{
private HubDemoService(IHubConnectionContext<dynamic> clients)
{
Clients = clients;
}
private IHubConnectionContext<dynamic> Clients
{
get;
set;
}
public static HubDemoService Instance { get; } = new HubDemoService(GlobalHost.ConnectionManager.GetHubContext<HubDemo>().Clients);
public void Hello()
{
Clients.All.Hello(true);
}
public void SendClient(string deviceSN)
{
Clients.Group(deviceSN).SendClient(" Device data ");
}
}
We use singleton mode for hub class and service class . And we used the grouping method , The concept of grouping is equivalent to wechat group , The message you send out can only be seen by this group , Other people can't receive the message you sent .
Let's see how to call the hub class SendClient Method to actively send data to the client . I am here Home A view has been added to the controller , This is a very simple view ,SignalR The client operation of is written in this view , The code is as follows :
public ActionResult SendClient()
{
return View();
}
public string AjaxPost()
{
HubDemo.Instance.SendClient("10000");
return "ajax return ";
}
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>SendClient</title>
</head>
<body>
<div>
<button id="btn1" onclick="btnclick()"> Send a request </button>
</div>
<script src="~/Scripts/jquery-3.4.1.js"></script>
<script src="~/Scripts/jquery.signalR-2.2.2.js"></script>
<script src="~/signalr/hubs"></script>
<script type="text/javascript">
var hubDemo = $.connection.HubDemo;
hubDemo.client.Hello = function (success) {
if (success) {
console.log(" Initialization connection succeeded !");
}
else {
console.log(" Failed to initialize connection !");
}
}
hubDemo.client.SendClient = function (data) {
console.log(data);
}
$.connection.hub.start().done(function () {
hubDemo.server.hello("10000");
});
function btnclick() {
$.ajax({
url: "/Home/AjaxPost",
type:"GET",
success: function (data) {
}
});
}
</script>
</body>
</html>
Want to use SignalR, You must add js In code 3 individual js, among /signalr/hubs yes SignalR Automatically generated .
stay start After completion , We called the server's hello Method to send the current device serial number to the server , The server will use this device serial number to generate a packet . When the server receives the data of the device serial number , Just send the data of the device to the current client , This avoids clients that do not listen to the current device receiving data from this device .
There is a place to pay attention to , Namely hello The case of this method , Although the server side Hello Method H It's in capital letters , But when the client calls ,H It must be in lowercase , Otherwise, the client will prompt you Hello It's not a way , Pictured :

There is another problem to pay attention to , That is, we can't return on the server View() Before sending data to the client , Such as :
public ActionResult SendClient()
{
HubDemo.Instance.SendClient("10000");
return View();
}
Because the server returns View() Then I'll be right html Load the page , Back in View() Previous call SendClient, In the corresponding view js The code hasn't been executed yet , So the client cannot receive data .
To solve this problem , I added a button to the interface , By clicking this button , Send a ajax Request , After the server receives the request , Then send the device data to the client . Trigger... By button ajax The request step is actually to simulate that the server receives the data sent by the device .
Start the program , Enter into SendClient, After the page loads , Click the send request button
The client output is as follows :

版权声明
本文为[begeneral]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230554082192.html
边栏推荐
- Copy constructor shallow copy and deep copy
- 【WPF绑定3】 ListView基础绑定和数据模板绑定
- Solution architect's small bag - 5 types of architecture diagrams
- Nifi fast installation and file synchronization
- freeCodeCamp----shape_ Calculator exercise
- Sub database and sub table & shardingsphere
- Promise (II)
- Detailed explanation of information abstract, digital signature, digital certificate, symmetric encryption and asymmetric encryption
- About stream flow, write it down briefly------
- 正则过滤内网地址和网段
猜你喜欢
![[PROJECT] small hat takeout (8)](/img/54/0187eeb637f4dcd4ad3969b00e2b77.png)
[PROJECT] small hat takeout (8)

Idea of batch manufacturing test data, with source code

Mock test

PyMySQL

Rtklib 2.4.3 source code Notes

Kunteng full duplex digital wireless transceiver chip kt1605 / kt1606 / kt1607 / kt1608 is suitable for interphone scheme

扫码登录的原理你真的了解吗?

English | day15, 16 x sentence true research daily sentence (clause disconnection, modification)

Getting started with JDBC

Change the password after installing MySQL in Linux
随机推荐
Node access to Alipay open platform sandbox to achieve payment function
websocket
Get the column name list of the table quickly in Oracle
RTKLIB 2.4.3源码笔记
Talk about browser cache control
Promise (III)
[markdown notes]
VLAN高级技术,VLAN聚合,超级Super VLAN ,Sub VLAN
Getting started with JDBC
Aiot industrial technology panoramic structure - Digital Architecture Design (8)
Copy constructor shallow copy and deep copy
vscode如何比较两个文件的异同
VLAN advanced technology, VLAN aggregation, super VLAN, sub VLAN
Mock test using postman
PHP高效读大文件处理数据
Promise (I)
_ Mold_ Board_
Pseudo Distributed installation spark
Read a blog, re understand closures and tidy up
1-2 JSX syntax rules