Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Case Analysis of WebSocket and Server push events in HTML5

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of "HTML5 WebSocket and server push event case analysis". The editor shows you the operation process through the actual case. The operation method is simple, fast and practical. I hope this "HTML5 WebSocket and server push event case analysis" article can help you solve the problem.

WebSockets

Web Sockets is a new generation of two-way communication technology for Web applications, which runs on a single socket and leaks into HTML5-compatible browsers through the JavaScript interface.

Once you have a Web Socket connection on the Web server, you can send data from the browser to the server by calling the send () method, and receive data from the server to the browser through the onmessage event handler.

Here is the API to create a new WebSocket object.

JavaScript Code copies content to the clipboard

Var Socket = new WebSocket (url, [protocal])

The first parameter, url, is used to specify the URL to connect to. The second attribute-the port is optional and, if provided, specifies that a server must support a successfully connected subprotocol.

WebSocket attribute

Here are the properties of the WebSocket object. Suppose we have created the above Socket object:

Attribute description

Socket.readyState

The read-only property readyState indicates the status of the connection. The following values are available:

0 indicates that the connection has not been established.

1 indicates that a connection is established and can communicate.

2 indicates that the connection is in the process of closing the handshake.

3 indicates that the connection is closed or cannot be opened.

Socket.bufferedAmount

The read-only property bufferedAmount represents the number of bytes of URF-8 text that have been queued using the send () method.

WebSocket event

Here are the events related to the WebSocket object. Suppose we have created the above Socket object:

Event handler description

This event is triggered when open Socket.onopen establishes a socket connection.

Triggered when a message Socket.onmessage client receives data from the server.

Triggered when an error occurs in the error Socket.onerror connection.

Triggered when a close Socket.onclose connection is closed.

WebSocket method

Here are the methods related to the WebSocket object. Suppose we have created the above Socket object:

Method description

Socket.send ()

The send (data) method uses connections to transfer data.

Socket.close ()

The close () method is used to terminate any existing connections.

Server push event

Traditional Web applications generate events that are sent to the Web server. For example, clicking a link will request a new page from the server.

This type of time from the Web browser to the Web server can be called a customer-side event.

With the advent of HTML5, WHATWG Web Applications 1.0 introduced a stream of events from the Web server to the Web browser, called server push events (SSE). Using SSE, you can constantly push DOM events to the user's browser.

This event flow method opens a persistent connection to the server and sends data to the client when new messages are available, eliminating the need for continuous polling.

SSE Web application

To use server push events in a Web application, we need to add an element to the document.

The src attribute of the element should point to a URL, and the URL should provide a HTTP persistent connection to send a data stream containing events.

This URL will point to a PHP,PERL or any Python script that continuously sends event data. The following is a simple example of a Web application that expects server time.

XML/HTML Code copies content to the clipboard

/ * Define event handling logic here * /

SSE server-side script

The server script should send the Content-type header to specify the type text/event-stream, as follows:

Copy the code

The code is as follows:

Print "Content-Type: text/event-stream/n/n"

After setting the Content-type, the server-side script sends an Event: tag followed by the event name. The following example will send a Server-Time that ends with a newline character as the event name.

Copy the code

The code is as follows:

Print "Event: server-time/n"

The final step is to send the event data using the Data: tag, followed by an integer string value that ends with a newline, as follows:

Copy the code

The code is as follows:

$time = localtime ()

Print "Data: $time/n"

Here is the complete ticker.cgi written in perl:

Copy the code

The code is as follows:

#! / usr/bin/perl

Print "Content-Type: text/event-stream/n/n"

While (true) {

Print "Event: server-time/n"

$time = localtime ()

Print "Data: $time/n"

Sleep (5)

Handle server push events

Let's modify our Web application to handle server push time. The following is the final example:

XML/HTML Code copies content to the clipboard

Document.getElementsByTagName ("eventsource") [0].

AddEventListener ("server-time", eventHandler, false)

Function eventHandler (event)

{

/ / Alert time sent by the server

Document.querySelector ('# ticker') [xss_clean] = event.data

}

[TIME]

Before testing server push events, it is recommended that you make sure that your Web browser supports this concept.

This is the end of the introduction to "WebSocket and server push event instance analysis of HTML5". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report