asp.net mvc implements simple real-time message push

https://www.cnblogs.com/ZERO-TAO/p/5713254.html

     Because of the needs of the project, it is necessary to implement the push of messages on the web page. I searched on Baidu and found that to achieve message push on web pages, you can use the SignalR class library in asp.net, and of course you can use H5's WebSocket Ajax cycle. Of course here we use the SignalR class library in asp.net. Because it can realize real-time push of messages on web pages. What is real-time push? Let me briefly talk about my personal understanding. Real-time: What happens at the same time, of course, is not absolutely real-time in the computer, because the CPU can only process one task in the same time slice, so the question comes again at this time? How do we usually use the computer, surf the Internet, and listen to music, because the computing speed of the current CPU is very fast. The CPU will process the time slices of different tasks, and the CPU will divide the time slices into very small, very small, so small that we humans cannot perceive them. For example, in the current time slice, the CPU is processing the music task, and in the next time slice, the CPU is processing the Internet access task again. So I think there is no absolute real-time in the computer, but we humans can't perceive it. Pushing: Pushing here refers to pushing messages on web pages. For example, users A and B respectively open the same message push webpage on their respective computers. Suppose user A now sends a message to user B. It is necessary to go through such a process User A->Server->User B. Of course, I will not discuss the specific underlying implementation process. Because this is not the subject of discussion now. Because the server has an address that is generally fixed. So it is easier for the client to send a message to the server because the destination address is fixed. How does the server send messages to the client? This is a bit confusing because the client's address is not fixed, and http is stateless and cannot remember the user's address. So in order to solve this problem. The predecessors of the computer used several methods, 1. The client "heartbeat". Visit the server every once in a while to see if the server has tasks for its clients. Ajax reincarnation is to use this method. The disadvantage is that the real-time performance is not very high. 2. The long connection between the server and the client is the idea used by SignalR in this article. Disadvantage: The pressure on the server is high.

      Well, now let's talk about what SignalR is. SignalR is a library for ASP.NET developers that simplifies the process of adding real-time web functionality to an application. Real-time web functionality refers to functionality where server code can push content to connected clients as soon as they become available, rather than having the server wait for clients to request new data. This also enables real-time push of messages. My personal understanding of the implementation principle is that the server first customizes a function for one client to call to send a message to another client. Of course, the client also needs to draw a function. Because the server needs to call this function of the client.

    Let's talk about the specific operation method below.

     1. Environment: win 10+VS2015 Community Edition

     I use asp.net mvc. First open VS 2015 | File | New | Project (SignalRMvc) | asp.net Web Application | Empty Template, MVC, the platform is probably like this.

     Now let's talk about the specific files that need to be included.

     1. SignalR hub class. Used to write a function that calls the client segment.

     2, OWIN class. The function used to register the server.

     3. The front page (including the writing of the message box in the foreground and the writing of the function), of course, the front desk needs some files.

    Generally, VS does not have its own SignalR class, and we need to add this function before starting the task. Select VS Tools | Nuget Package Manager | Nuget Package Manager Console | Install-Package Microsoft.Aspnet.SignalR to install SignalR. After the installation is complete, 1. We create a new folder in the project called ChatHubs|Create a new SignalR hub class, and write the following code:

copy code
using Microsoft.AspNet.SignalR;

namespace SignalRMvc.ChatHubs
{
    public  class ChatHub: Hub
    {
        public void SendMessage(string name,string message)
        {
            //   Clients.All.hello(); 
            Clients.All.receiveMessage(name, message);
             // User calls the client's function 
        }
    }
}
copy code

 2. Create a new OWIN class in the ChatHubs folder. and write the following code:

copy code
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(SignalRMvc.ChatHubs.Startup))]

namespace SignalRMvc.ChatHubs
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
            // The hub registration of the server 
        }
    }
}
copy code

3. Create a new Home controller in Controllers. and write the following code:

copy code
using System.Web.Mvc;

namespace SignalRMvc.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult ClientChat()
        {
            return View();
        }
    }
}
copy code

4、在控制器的方法上右击添加视图(不使用模板,也不使用布局页)后。并写上如下代码:

copy code
@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <meta charset="utf-8" />
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    @* BootStarp的引入*@
    <style>
        #message_box {
            height: 400px;
            overflow-y: scroll;
        }
    </style>
    @* 呈现消息 *@
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="jumbotron">
                <ul id="message_box"></ul>
            </div>
            发送者名称:<input id="text_name" class="form-control" /><br />
            消息内容:
            <textarea id="text_message" class="form-control" rows="3"></textarea>
            <br />
            <button id="btn_send" class="btn btn-block btn-success">Send</button>
        </div>
    </div>

    <script src="~/scripts/jquery-3.1.0.min.js"></script>
    <script src="~/scripts/jquery.signalR-2.2.1.min.js"></script>
    @* 上述引入的两个文件的顺序不以交换,因为下面这个文件依赖于上面那个文件 *@
    <script src="~/signalr/hubs"></script>
    <!-- 本地没有,动态生成 -->
    <script>
        $(function () {
            var $messageBox = $('#message_box');
            var $textMessage = $('#text_message');
            var $textName = $('#text_name');
            //客户端先与服务器连接起来,拿到服务器的代理操作对象
            var hubConnection = $.connection.chatHub;
            //注册客户端函数
                hubConnection.client.receiveMessage = function (name, message) {
                $messageBox.append('<li><b>' + name + '</b> say:' + message + '</li>')
            }

            //启动连接到服务器
            $.connection.hub.start().done(function () {
                $('#btn_send').bind('click', function () {
                    //调用服务端的函数
                    hubConnection.server.sendMessage($textName.val(), $textMessage.val());
                });
            });
        });
    </script>
</body>
</html>
copy code

If directly copied to use. Pay attention to the directory and version of the file introduced by the code in the foreground. The first letter of the name of the front-end code is best to use lowercase, and the first letter of the back-end code is best to use uppercase. Because js uses camel case by default, C Sharp uses Pascal naming. If you don't pay attention to this detail, it will be easy to make mistakes. Because the background code will dynamically generate some JS code when it is executed, the default camel case for JS code is used. It's easy to make mistakes if you use Pascal naming in your frontend code. And it's not easy to find. I have experienced it myself.

Let's test locally: use FireFox and Chrome to simulate two clients, of course, our own computer is also the server. The effect diagram is as follows:

Of course I'm a rookie of a rookie. There must be a lot of misunderstandings. Hope you guys can point it out.

To add, you can refer to the official website of asp.net. http://www.asp.net/signalr/overview/getting-started/tutorial-getting-started-with-signalr-and-mvc. Of course, you can also take a look at the related video, I think it is the video on the Chuanzhi podcast, and the code also follows the video step by step. It's not advertising, it's just pure technology sharing. Writing a blog is to sort out specific methods and ideas, and of course to write about my own understanding of this thing.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325728849&siteId=291194637