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

What is the use of WebSocket protocol in HTML5

2025-02-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article is to share with you about the usefulness of the WebSocket protocol in HTML5. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

1. Background

In order to implement the push technology, many websites use Ajax polling. Polling is a browser in which the browser sends a HTTP request to the server at a specific time interval, and then the server returns the latest data to the client. This traditional mode brings obvious disadvantages, that is, browsers need to constantly send requests to the server, but HTTP requests may contain long headers, in which the really effective data may be only a small part, which will obviously waste a lot of bandwidth and other resources. Some new protocols added by HTML5, WebSocket, can provide full-duplex, two-way communication on a single TCP connection, save server resources and bandwidth, and communicate in real time.

2. WebSocket introduction

Traditional http is also a kind of protocol, and WebSocket is a kind of protocol, so it is impossible to implement WebSocket with http server.

2.1. Browser support

Basic mainstream browsers support it.

2.2. Advantages

Compared to http, it has the following advantages:

1. Only one TCP connection is established between the client and the server, and fewer connections can be used.

The 2.WebSocket server can actively push data to the client, which is more flexible and efficient.

3. A more lightweight protocol header to reduce the amount of data transmission.

Comparison of rotational training mechanism

3. WebSocket usage

After we know what WebSocket is and what its advantages are, how to use it?

3.1.WebSocket creation

WebSocket uses a custom protocol, url mode is slightly different from http, unencrypted connections are ws://, encrypted connections, wss://,WebSocket instances use the new WebSocket () method to create

Var ws = new WebSocket (url, [protocol])

The first parameter, url, specifies the URL of the connection. The second parameter, protocol, is optional and specifies an acceptable subprotocol.

3.2.WebSocket attribute

When a ws object is created, readyState is in the ws instance state, with a total of four states

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 being closed.

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

Tips: to judge the status before sending a message, disconnection should also have a reconnection mechanism.

3.3.WebSocket event

After the ws instance object is created, you will have the following events, which can be called back to write methods based on different states.

Triggered when a ws.onopen connection is established

Triggered when a ws.onmessage client receives server data

Triggered when an error occurs in ws.onerror communication

Triggered when the ws.onclose connection is closed

Ws.onmessage = (res) = > {console.log (res.data);}; ws.onopen = () = > {console.log ('OPEN...');}; ws.onclose= () = > {console.log (' CLOSE...');}

3.4.WebSocket method

Ws.send () sends data using a connection (only plain text data can be sent)

Ws.close () closes the connection

4. Demo demonstration

After learning about some API of WebSocket, strike while the iron is hot and run a small case.

4.1.Node server side

The WebSocket protocol works very well with Node for two reasons:

1.WebSocket client event-based programming is similar to custom events in Node.

2.WebSocket implements a long connection between the client and the server, and the basic event-driven method of Node is very suitable for high concurrent connections.

Create a webSocket.js as follows:

Const WebSocketServer = require ('ws'). Server;const wss = new WebSocketServer ({port: 8080}); wss.on (' connection', function (ws) {console.log ('client connected'); ws.on (' message', function (message) {ws.send ('I received 'message);});})

Open the windows command window to run

4.2.HTML client

Create a new index.html page:

WebSocket Little Demo

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