当前位置:网站首页>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
边栏推荐
- Tencent resolves the address according to the IP address
- About stream flow, write it down briefly------
- Promise (I)
- Go language RPC communication
- ACL 2022 | DialogVED:用于对话回复生成的预训练隐变量编码-解码模型
- Preliminary understanding of promse
- PostgreSQL column storage and row storage
- Do you really understand the principle of code scanning login?
- Interface document yaml
- 1-2 characteristics of nodejs
猜你喜欢
STM32__ 03 - beginner timer
[pimf] openharmony paper Club - what is the experience of wandering in ACM survey
Change the password after installing MySQL in Linux
Milvus 2.0 質量保障系統詳解
True math problems in 1959 college entrance examination
【WPF绑定3】 ListView基础绑定和数据模板绑定
Rtklib 2.4.3 source code Notes
Idea of batch manufacturing test data, with source code
Bytevcharts visual chart library, I have everything you want
Document operation II (5000 word summary)
随机推荐
【生活中的逻辑谬误】稻草人谬误和无力反驳不算证明
Rtklib 2.4.3 source code Notes
Multithreaded @ async thread pool
ACL 2022 | dialogved: a pre trained implicit variable encoding decoding model for dialogue reply generation
Baidu Map Case - Zoom component, map scale component
1-2 characteristics of nodejs
Wiper component encapsulation
Calculation formula related to tolerance analysis
Nacos + aspnetcore + Ocelot actual combat code
Handwritten event publish subscribe framework
Promise (I)
正则过滤内网地址和网段
How to implement distributed locks with redis?
Baidu Map 3D rotation and tilt angle adjustment
1-3 nodejs installation list configuration and project environment
Use between nodejs modules
深入了解3D模型相关知识(建模、材质贴图、UV、法线),置换贴图、凹凸贴图与法线贴图的区别
Bottom processing of stack memory in browser
◰GL-着色器处理程序封装
Nodejs installation and environment configuration