Home >Web Front-end >H5 Tutorial >A brief analysis of HTML5's WebSocket and server push events_html5 tutorial skills
WebSockets
Web Sockets is a new generation of two-way communication technology for web applications, running on a single socket, which is exposed in HTML5-compatible browsers through a JavaScript interface.
Once you have obtained the 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.
The following is the API to create a new WebSocket object.
The first parameter url is used to specify the URL to connect to. The second attribute - port is optional and, if provided, specifies a subprotocol that the server must support for a successful connection.
WebSocket Properties
The following are the properties of the WebSocket object. Assume we have created the above Socket object:
Attribute | Description | |||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Socket.readyState |
readyState represents the status of the connection. It has the following values:
1 means the connection is established and communication is possible.
|
|||||||||||||||||||||||||||
Socket.bufferedAmount | Read-only attributebufferedAmountRepresents the number of URF-8 text bytes that have been queued using the send() method. |
Method | Description |
---|---|
Socket.send() | The send(data) method uses a connection to transfer data. |
Socket.close() | The close() method is used to terminate any existing connection. |
Server Push Events
Traditional web applications generate events that are sent to the web server side. 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 client-side event.
With the advent of HTML5, WHATWG Web Applications 1.0 introduced an event stream from the web server to the web browser called Server Push Events (SSE). Use SSE to continuously push DOM events to the user's browser.
This event streaming method will open a persistent connection to the server and send 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
This URL will point to a PHP, PERL or any Python script that continuously sends event data. Here is a simple example of a web application that expects the server time.
SSE server-side script
Server-side script should send Content-type header specifying the type as text/event-stream, as shown below:
Handling server push events
Let’s modify our web application to handle server push events. Here is the final example:
在测试服务器推送事件之前,建议你确保你的 Web 浏览器支持这一概念。