当前位置:网站首页>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