search
HomeWeb Front-endH5 TutorialDetailed explanation of H5 server push events

Detailed explanation of H5 server push events

Mar 26, 2018 pm 05:40 PM
html5serverDetailed explanation

This time I will bring you a detailed explanation of H5 server push events, and what are the precautions for server push events. The following is a practical case, let’s take a look.

Server-sent Events are a one-way communication based on the WebSocket protocol in which the server sends events & data to the client. All major browsers currently support server-sent events, except Internet Explorer of course. 2333...

WebSocket protocol is another server-client communication protocol after the HTTP protocol. Different from HTTP's simple one-way communication mode where the client requests the server to respond, it supports two-way communication between the server and the client. .

The use of Server-sent Events

Server-sent Events (hereinafter referred to as SSE) as the server => client communication method is inevitable The client must have a corresponding service address and response method, and the server must have a corresponding data sending method; without further ado, let’s get to the code!

Client-side JS code

The H5 page needs to add the following JS code:

     <script>
         if (typeof (EventSource) !== "undefined") {
             //推送服务接口地址
             var eventSource = new EventSource("http://localhost:2242/webservice/ServerSent/SentNews");
             //当通往服务器的连接被打开
             eventSource.onopen = function () {
                 console.log("连接打开...");
             }
              //当错误发生
              eventSource.onerror= function (e) {
                  console.log(e);
              };
              //当接收到消息,此事件为默认事件
              eventSource.onmessage = function (event) {
                  console.log("onmessage...");
               eventSource.close()//关闭SSE链接
              };
              //服务器推送sentMessage事件
              eventSource.addEventListener(&#39;sentMessage&#39;, function (event) { 
                  var data = eval(&#39;(&#39;+event.data+&#39;)&#39;);//服务器端推送的数据,eval装换Json对象
                  var origin = event.origin;//服务器 URL 的域名部分,即协议、域名和端口,表示消息的来源。
                  var lastEventId = event.lastEventId;////数据的编号,由服务器端发送。如果没有编号,这个属性为空。
                  //此处根据需求编写业务逻辑
                  console.log(data);              }, false);
          } else {
              //浏览器不支持server-sent events 所有主流浏览器均支持服务器发送事件,除了 Internet Explorer。
              document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
          }
      </script>

Server-side

What data format should the server return? What kind of response should be given to the client? Let’s take a .Net example first

    /// <summary>
        /// 推送消息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage SentNews()
        {
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
            try
            {
                //response.Headers.Add("Access-Control-Allow-Origin", "*");//如需要跨域可配置
                string data_str = “推送至客户端的数据”;//当然可以是json字符串格式
                string even = "", data = "";
                if (!string.IsNullOrWhiteSpace(data_str))
                {
                    even = "event:sentMessage\n";
                    data = "data:" + data_str + "\n\n";
                }
                string retry = "retry:" + 1000 + "\n";//连接断开后重连时间(毫秒),其实可以理解为轮询时间 2333...
                byte[] array = Encoding.UTF8.GetBytes(even + data + retry);
                Stream stream_result = new MemoryStream(array);
                response.Content = new StreamContent(stream_result);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/event-stream");//此处一定要配置
                response.Headers.CacheControl = new CacheControlHeaderValue();
                response.Headers.CacheControl.NoCache = false;
            }
            catch (Exception ex)
            {
                LogHelper.WriteWebLog(ex);
            }
            return response;
        }

After reading the above code, I think you should have a rough idea. The response method is still HTTPResponse response, but there are always some small requirements:

Response header "Content-Type" should be set to "text/event-stream"

The response data format should also note the "data:", "event:" and "retry:" in the above code These tags:

1.event: Indicates the type of event used by this line to declare. When the browser receives data, it will generate events of the corresponding type.

2.data: Indicates that the row contains data. Lines starting with data can appear multiple times. All these rows are data for that event.

3.retry: Indicates that this line is used to declare the waiting time of the browser before reconnecting after the connection is disconnected.

4.id: Indicates the identifier (that is, the number of the data) used by this row to declare the event, which is not commonly used.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to solve the problem that the video tag in H5 cannot play mp4 files

H5’s multi-threading (Worker SharedWorker) detailed explanation

Use phonegap to clone and delete contacts

The above is the detailed content of Detailed explanation of H5 server push events. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

H5 Code: Writing Clean and Efficient HTML5H5 Code: Writing Clean and Efficient HTML5Apr 20, 2025 am 12:06 AM

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

H5: How It Enhances User Experience on the WebH5: How It Enhances User Experience on the WebApr 19, 2025 am 12:08 AM

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.

Deconstructing H5 Code: Tags, Elements, and AttributesDeconstructing H5 Code: Tags, Elements, and AttributesApr 18, 2025 am 12:06 AM

HTML5 code consists of tags, elements and attributes: 1. The tag defines the content type and is surrounded by angle brackets, such as. 2. Elements are composed of start tags, contents and end tags, such as contents. 3. Attributes define key-value pairs in the start tag, enhance functions, such as. These are the basic units for building web structure.

Understanding H5 Code: The Fundamentals of HTML5Understanding H5 Code: The Fundamentals of HTML5Apr 17, 2025 am 12:08 AM

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

H5 Code: Best Practices for Web DevelopersH5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AM

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version