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 real-time communication mode of the web front-end?

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

Share

Shulou(Shulou.com)05/31 Report--

Most people do not understand the knowledge points of this article "what is the way of web front-end real-time communication?", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "what is the way of web front-end real-time communication".

1. Short polling

The principle of short polling is very simple. Every once in a while, the client sends a request to get the latest data from the server, which simulates the realization of instant messaging to a certain extent.

Advantages: strong compatibility, very simple to implement

Disadvantages: high latency, most of the requests are useless, very consuming bandwidth and server resources, affecting performance

Application: QR code scan confirmation, information notification

Implementation method:

Using timer to realize short polling

Created () {this.shortPolling = setInterval (function () {that.getRuset ()}, 5000)},... getResult () {var that = this this.$axios ('xxx,') Post) .then (res= > {if (res.code = 200) {/ / get the desired result. / / whether the timer is cleared or not is determined by the business scenario clearInterval (this.shortPolling)}} 2.comet (long polling, long connection)

There are two main ways to implement comet, one is long polling (long-polling) based on AJAX, and the other is streaming based on Iframe and htmlfile, which is usually called persistent connection.

For the specific operation methods of the two means, please step into the Comet technology: real-time communication technology on the Web side based on HTTP long connection

2.1. Long polling

The client sends an Ajax request to the server, and after receiving the request, the server hold stops the connection, returns the response information and closes the connection until there is a new message, and the client sends a new request to the server after processing the response information.

Advantages: good compatibility, less frequent requests in the absence of messages, less waste of resources

Disadvantages: server hold connections will consume resources, the order of returned data is not guaranteed, and it is difficult to manage and maintain

Applications: webQQ, Kaixin, campus, Hi web version, Facebook IM, etc.

Implementation method:

It is mainly connected by the back-end hold, and we just send the request normally.

GetResult () {var that = this this.$axios ('xxx,',post) .then (res= > {if (res.code = 200) {...} else {this.getResult ()})}

Normally, our frontend sets the request timeout, so we agree with the backend that the result must be returned at the frontend within the timeout range.

2.2, long connection

Embed a hidden iframe in the page, set the src property of the hidden iframe to a persistent connection request or use a xhr request, and the server can continuously input data to the client. This method is out of date and I recommend it. After all, iframe has been abandoned now.

Advantages: good compatibility, instant message arrival, no useless requests

Disadvantages: server maintenance of persistent connections consumes resources

Example: Gmail chat

Implementation method:

/ / embed iframewatchIframe () in vue {/ / find the window of iframe first this.iframeWin = this.$refs.iframe.contentWindow; / / send a message to iframe, and the content sent is in curly braces; this.iframeWin.postMessage ({}, "*") / / how to monitor the information sent by iframe window.addEventListener ("message", this.handleMessage); / / to get the information from iframe handleMessage (res) {/ / res is the incoming message. / / rendering page}} 3.SSE user guide please see the Server-Sent Events tutorial

SSE (Server-Sent Event) is a HTML5 technology that allows the server to push new data to the client.

Advantages: based on HTTP, it can be used without much modification and easy to use, while websocket is very complex and must rely on mature libraries or frameworks.

Disadvantages: based on the text transmission efficiency is not as efficient as websocket, not strict two-way communication, the client sends a request to the server can not reuse the previous connection, it needs to reissue an independent request, and is not compatible with IE

Source.addEventListener ('open', function (event) {/ /...}, false); / / when the client receives data from the server, it triggers the message event, which can be found in the callback function of the onmessage attribute. Source.addEventListener ('message', function (event) {var data = event.data; / / handle message}, false); / / if a communication error occurs (such as a connection break), the error event is triggered, and the callback function can be defined in the onerror attribute. The source.addEventListener ('error', function (event) {/ / handle error event}, false) / / close method is used to close the SSE connection. Source.close ()

We can also customize events, and there are clear ways to use them in the Server-Sent Events tutorial.

4.Websocket

Websocket is a new and independent protocol, based on TCP protocol, which is compatible with http protocol, but will not be integrated into http protocol. As a part of html5, its function is to establish real-time two-way communication between server and client.

Advantages: real-time two-way communication, good performance and low delay

Disadvantages: independent of http protocol, so requires additional project modification, high complexity, must introduce mature libraries, can not be compatible with low-version browsers

Implementation method:

The browser provides a XMLHttpRequest object for HTTP communication. Similarly, it also provides a communication operation interface for WebSocket communication: WebSocket.

Var ws = new WebSocket ("wss://echo.websocket.org"); / / when the connection is successfully established, trigger the open event ws.onopen = function (evt) {console.log ("connection successfully established..."); / / after the connection is established, you can use this connection object to communicate / / send method to send data ws.send ("Hello WebSockets!");} / / when receiving the message sent by the other party, trigger the message event / / We can get the data content sent by the other party through the evt.data of the callback function ws.onmessage = function (evt) {console.log ("received message:" + evt.data); / / when communication is not needed, you can manually close the connection / / ws.close ();} / / trigger the close event ws.onclose = function (evt) {console.log ("connection closed.") when the connection is disconnected;} 5.Web Worker

The role of Web Worker is to create a multithreaded environment for JavaScript, allowing the main thread to create Worker threads and assign some tasks to the latter to run

Advantages: implementing a multithreaded environment, getting rid of the single thread of js

Disadvantages: unable to access DOM node; unable to access global variables or global functions; unable to call functions such as alert () or confirm; unable to access browser global variables such as window and document

Note: Javascript in Web Worker can still use functions such as setTimeout () and setInterval (), or you can use the XMLHttpRequest object for Ajax communication.

Example: big data's processing; high-frequency user interaction:

Implementation method:

Web workers can be divided into two types: dedicated threads and shared threads.

The dedicated thread ends with the closure of the current page; this means that the dedicated thread can only be accessed by the page that created it.

The corresponding shared thread can be accessed by multiple pages.

5.1, dedicated thread

Use onmessage (), postmessage () to communicate

/ * * main thread * * / / Register dedicated thread let worker = new Worker ('worker.js') worker.onmessage = (e) = > {console.log (e.data) / / I post a message to main thread} worker.postMessage (' main thread got a message') / * * child thread worker.js * / onmessage = (e) = > {console.log (e.data) / / main thread got a message} postMessage ('I post a message) To main thread') / / terminate worker.terminate () in the main thread / / terminate itself in the child thread self.close () 5.2, Shared thread

Port attribute is required for SharedWorker, and connect is required for receiving.

/ / register shared thread let worker = new SharedWorker ("sharedworker.js"); / * * main thread * * / worker.port.onmessage = function (e) {} worker.port.postMessage ('data'); / * * child thread * * / addEventListener (' connect', function (event) {var port = event.ports [0] / / receive port.onmessage = function (event) {console.log (event.data);} / / send port.postMessage ("data"); port.start ();}); / / terminate worker.terminate () in the main thread / / terminate itself self.close () in the child thread

Two ways of error monitoring are the same as SSE

Worker.addEventListener ("error", function (evt) {alert ("Line #" + evt.lineno + "-" + evt.message + "in" + evt.filename);}, false); worker.postMessage (10000);}; 6.Service workers

Service workers essentially acts as a proxy server between Web applications and browsers, and can also act as a proxy between browsers and networks when the network is available, creating an effective offline experience. It is a type of Web Worker

Advantages: can be accessed in seconds or offline

Disadvantages: IE11, Opera Mini, IOS do not support

Application: push Notification-  allows users to select timely updates from web applications.

Implementation method:

/ / serviceWorker.jsimport {register} from 'register-service-worker'if (process.env.NODE_ENV =' production') {register ('service-worker.js', {ready () {console.log (' App is being served from cache by a service worker.')}, registered () {console.log ('Service worker has been registered.')} Cached () {console.log ('Content has been cached for offline use.')}, updatefound () {console.log (' New content is downloading.')}, updated () {console.log ('New content is available) Please refresh.') _ window.location.reload (true) / / the page needs to be refreshed here}, offline () {console.log ('No internet connection found. App is running in offline mode.')}, error (error) {console.error ('Error during service worker registration:', error)}})}

Join in plugins

Plugins: [new SWPrecacheWebpackPlugin ({cacheId: 'my-project-name', filename:' service-worker.js', staticFileGlobs: ['dist/**/*. {js,html,css}'], minify: true, stripPrefix: 'dist/'}), new WebpackPwaManifest ({name:' My Progressive Web App', short_name: 'MyPWA', description:' My awesome Progressive Web appendage' Background_color:'# ffffff', crossorigin: 'use-credentials', / / can be null, use-credentials or anonymous icons: [{src: path.resolve (' src/assets/icon.png'), sizes: [96,128,192,256,384,512] / / multiple sizes}, {src: path.resolve ('src/assets/large-icon.png') Size: '1024x1024' / / you can also use the specifications pattern}]}), / /...]

At this time, a service-worker.js is added to the root directory of the packaged code, and the pwa-related elements are also added to the html file.

Introduce this file in the entry main.js:

Import'. / serviceWorker'7, Flash Socket

A Flash program JavaScript, which uses the Socket class, is embedded in the page to communicate with the Socket interface of the server by calling the Socket interface provided by the Flash program. JavaScript controls the display of the page after receiving the information sent by the server. Generally used in online games, the web side is basically not applicable, plus as early as July 2017, Flash's family Adobe has announced that it will end its support for Flash at the end of 2020. Browsers will also end their support for Flash around the end of 2020.

Pros: achieve real instant messaging, not pseudo-instant messaging.

Disadvantages: the client must install the Flash plug-in; non-HTTP protocol, can not automatically pass through the firewall.

Example: online interactive games.

Implementation method: because it has been abandoned, and I am not a game front-end, I do not understand the implementation of Flash, interested partners can study it on their own

The above is the content of this article on "what is the way of real-time communication at the front end of web?" I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more related knowledge, please pay attention to the industry information channel.

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