The most comprehensive in the history of SignalR series of tutorials -3, SignalR achieve push function - Hubs class implementation

1 Overview

By the first two

History of the most comprehensive series of tutorials SignalR -1, understanding SignalR

The most comprehensive in the history of SignalR series of tutorials -2, SignalR achieve push function - permanently connected class implementation

Articles on the introduction of SignalR, we have a comprehensive understanding of SignalR. Communication SignalR API client and server persistent connection, a connection on behalf of a single transmission, or broadcast message packets simple terminal. API persistent connections (the PersistentConnection performance in the .NET class) to the conditions for developers low-cost access to the communication protocol of SignalR exposed. Using this connection, as developers use the same WCF.

This article deals continue on the basis of previous, explain SignalR implement the message sent by the push and the most common way hub.
We know SignalR communication model is mainly two kinds of Persistent Connections and Hubs. Hub is a more advanced pipeline, which allows the client and server on the connection protocol can directly call each method. This SignalR automatic distribution across machine boundaries scheduling method as if by magic, so that the client calls the server method is as simple as calling a local, and vice versa. Use Hub model as developers use remote API, such as .NET Remoting. Hub allows you to use the same type of pass parameters to the method of model binding. Hubs implement message server to the client pushed through, as an abstract structural view.

SignalR Hub structure flowchart

2, SignalR Hub principle analysis

SignalR specifically how to get to the implementation of it? SignalR implementation mechanism Remoting and .NET WCF or similar, are using remote agents to achieve. SignalR the entire connection, the clearing process is very beautiful package, all the client and server to exchange data using JSON.

When the end of the service code access method of a client, a packet is automatically transmitted, data packet includes a name of a function of the method parameters (if an object, then the object is serialized as JSON). Then according to the code matching method name of the client a client. If the corresponding matching method is found, call the appropriate function to perform long deserialize parameter.

3, Hubs real-time message flow

  • The server corresponding to the definition hub class;

  • Defined at the client proxy class corresponding hub class;

  • Establish the connection (connection) between the client and the server;

  • Then the client can call the proxy object method to invoke server-side methods, that is, send request to the server;

  • After the server receives the request, for a possible / group of clients or all clients (broadcast) to send a message.

Process Communication Model SignalR Hubs

4, SignalR connected to the Hub class implemented Mvc

We continue on an Extended hubs of the project on the basis of the way. Specific new projects, references, etc. can add signalr on a reference.

4.1, added to the project HubConnections directory in which to add ChatHub.cs file, as shown below:

New charthub file

Code reads as follows:

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

namespace SignalRTestProj.HubConnections
{
    //HubName 这个特性是为了让客户端知道如何建立与服务器端对应服务的代理对象,
    //如果没有设定该属性,则以服务器端的服务类名字作为 HubName 的缺省值
    [HubName("chat")]
    public class ChatHub : Hub 
    {
        public void Send(string clientName, string message)
        {
            // Call the addSomeMessage method to update clients.
            Clients.All.addSomeMessage(clientName, message);
        }
    }
}

In the above code, the realization of the service is very simple, is that when a client calls the Send method to send message to the server, the server is responsible for the message broadcast to all clients (also can give a specific group or a specific client), to implement the functions of the chat room.

In addition to the server can inform the client calls the method to all clients, but also can be sent to the client which wants to restrict. Meanwhile Clients This property has a lot of dynamic members for our use:

Clients.All:允许“调用”连接到此Hub上的所有客户端的一个方法

Clients.AllExcept:表示该调用必须发送给所有客户端,但是除了那些作为参数的connectionId以外。这里的参数可以是connectionId字符串、数组等

Clients.Caller 确定调用者的接收者是目前调用正在执行Hub方法的客户端

Clients.Client:将对方法的调用发送给指定connectionId的客户端,参数可以是字符串,也可以是数组

Client.Others :代表所有已连接的客户端,但是不包括正在调用该方法的客户端。

在方法中可以通过访问 this.Context.ConnectionId来获得当前掉用方法的客户端唯一标识符

1), HubName this feature is to let the client know how to build server-side proxy object corresponding to the service, if the property is not set, places the server-side service class name as the default value of HubName;

2), ChatHub inherited from the Hub, Hub interface from the following can be seen: Hub support to initiate the requester (Caller), all clients (Clients), a specific group (Group) push message.

Hub graph object definition

3)、public void Send(string clientName, string message) 这个接口是被客户端通过代理对象调用的;

4)、Clients 是 Hub 的属性,表示所有链接的客户端页面,它和 Caller一样是 dynamic,因为要直接对应到 Javascript 对象;

5)、Clients.All.addSomeMessage(clientName, message): 表示服务器端调用客户端的 addSomeMessage 方法,这是一个 Javascript 方法,从而给客户端推送消息。

4.2、配置启动类

using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(SignalRTestProj.App_Start.ChartStartup))]

namespace SignalRTestProj.App_Start
{
    public class ChartStartup
    {
        public void Configuration(IAppBuilder app)
        {
            // 有关如何配置应用程序的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkID=316888
            //1、 PersistentConnection 方式配置
            //app.MapSignalR<ChatConnection>("/Connections/ChatConnection");

            //2、hub方式配置    
            app.MapSignalR();          
        }
    }
}

4.3、页面代码实现

<h2>Hub Chat</h2>

<div>
    <input type="hidden" id="ClientName" value="@ViewBag.ClientName"/>
    <input type="text" id="msg" />
    <input type="button" id="broadcast" value="广播" />
    <br />

    <h3>
        (<span id="MyClientName">@ViewBag.ClientName</span>):
    </h3>

    <ul id="messages"></ul>
</div>

@section scripts {
    <script src="~/Scripts/jquery-3.3.1.min.js"></script>
    <script src="~/Scripts/jquery.signalR-2.4.1.min.js"></script>
    <script src="~/signalr/hubs"></script>
    <script>
        $(function () {            
            var chat = $.connection.chat;
            var myClientName = $('#ClientName').val();            
            chat.client.addSomeMessage = function (clientName, message) {
                writeMsg('<b>' + clientName + '</b> 对大家说: ' + message, 'event-message');
            };

            $('#msg').focus();
            // 开始连接
            $.connection.hub.start().done(function () {
                $('#broadcast').click(function () {
                    // 调用send方法
                    chat.server.send(myClientName, $('#msg').val());                   
                    $('#msg').val('').focus();
                });
            });

            //写消息
            function writeMsg(eventLog, logClass) {
                var now = new Date();
                var nowStr = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
                $('#messages').prepend('<li class="' + logClass + '"><b>' + nowStr + '</b> ' + eventLog + '.</li>');
            }
        });
    </script>
}

在上面的代码我们

1、首先获取客户端页面的名字;

2、然后通过 $.connection.chat 建立对应服务器端 Hub 类的代理对象 chat;

3、定义客户端的 Javascript 方法 addSomeMessage,服务器通过 dynamic 方式调用客户端的该方法以实现推送功能。在这里每当收到服务器推送来的消息,就在客户端页面的 messages 列表表头插入该消息。

4、当点击广播按钮时,客户端通过代理对象调用服务器端的 send 方法以实现向服务器发送消息。

5、通过 $.connection.hub.start(); 语句打开链接。

5、效果展示

Operating results show

6、代码下载

实例源码可以移步github下载,地址:https://github.com/yonghu86/SignalRTestProj

7、参考文章


Along the way a number of years, thanks to supporters and users RDIFramework.NET framework, we can use the following address for more information.

RDIFramework.NET official website: http: //www.rdiframework.net/

RDIFramework.NET official blog: http: //blog.rdiframework.net/

It should be noted at the same time, all future technical articles subject to the official website, welcome to the collection!

RDIFramework.NET framework to build long-term thinking by the Hainan State Software Technology Co., Ltd. professional team, has been updated, has been upgraded, ease of use!

Welcome to the framework of official public attention RDIFramework.net micro letter (Micro Signal: guosisoft), keep abreast of the latest developments.

Scan the QR code immediate attention

Micro Signal: guosisoft

Guess you like

Origin www.cnblogs.com/huyong/p/11344828.html