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

How the html5 server pushes Server-sent Events and websocket

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

In this issue, the editor will bring you about how html5 servers push Server-sent Events and websocket. The article is rich in content and analyzes and describes for you from a professional point of view. I hope you can get something after reading this article.

Html5's server pushes Server-sent Events and websocket

Server-Sent Events

Operation principle

The browser sends a request to the server through HTTP. The server takes out the latest information in the database and returns it to the client immediately. The client waits for three seconds and then sends out the next request again.

Mode of realization

The JavaScript module opens the EventSource and passes the recipient's id to the server. After the client receives the corresponding, the handler of the onMessage event will be called. The browser will send a request every 3 seconds unless the connection is closed (Close method).

Client example: JS Binif (typeof (EventSource)! = = "undefined") {var source = new EventSource ('http://127.0.0.1:8844/stream'); var div = document.getElementById (' example'); source.onopen = function (event) {div [XSS _ clean] + ='

Connection open...

';}; source.onerror = function (event) {div [XSS _ clean] + ='

Connection close.

';}; source.addEventListener (' connecttime', function (event) {div [XSS _ clean] + = ('

Start time:'+ event.data +'

');}, false); source.onmessage = function (event) {div [XSS _ clean] + = ('

Ping:'+ event.data +'

');};} else {/ / browser does not support Server-Sent..} / / source.close (); / / close the connection method EventSource object

In the above example, we use the onmessage event to get the message. However, other events can be used:

Event description onopen when the connection to the server is opened onmessage when the message onerror when an error occurs nodejs server example:

The syntax of the server-side event flow is very simple. Set the Content-Type header to text/event-stream.

Content-Type: text/event-stream

Cache-Control: no-cache

Connection: keep-alive

Fields returned by the server:

Data: data content

Event: custom event

Id: data number

Retry: specifies the interval at which the browser reinitiates the connection. Retry: 10000\ n

:: a line that begins with a colon, indicating a comment

Two situations can cause the browser to re-initiate the connection:

One is that the time interval expires, and the other is due to network errors and other reasons, resulting in connection errors.

Var http = require ("http"); http.createServer (function (req, res) {var fileName = "." + req.url; if (fileName = = ". / stream") {res.writeHead (200,{ "Content-Type": "text/event-stream", "Cache-Control": "no-cache", "Connection": "keep-alive", "Access-Control-Allow-Origin":'*',}) Res.write ("retry: 10000\ n"); res.write ("event: connecttime\ n"); res.write ("data:" + (new Date ()) + "\ n\ n"); res.write ("data:" + (new Date ()) + "\ n\ n"); interval = setInterval (function () {res.write ("data:" + (new Date ()) + "\ n\ n");}, 1000)) Req.connection.addListener ("close", function () {clearInterval (interval);}, false);}) .req.connection.addListener (8844, "127.0.0.1"); WebSockets

Return to the directory

Operation principle

The client notifies the WebSockets server of an event, telling him the recipient id, the server will immediately notify the message, and when any new unread message comes, the server will immediately return the data to the client.

Client example: function WebSocketTest () {if ("WebSocket" in window) {alert ("your browser supports WebSocket!"); / / Open a web socket var ws = new WebSocket ("ws://localhost:8181"); ws.onopen = function () {/ / WebSocket is connected and use the send () method to send data ws.send ("send data"); alert ("data sending...") }; ws.onmessage = function (evt) {var received_msg = evt.data; alert ("data received.");}; ws.onclose = function () {/ / close websocket alert ("connection closed.");};} else {/ / browser does not support WebSocket alert ("your browser does not support WebSocket!") }} socket server nodejsvar net = require ("net"); server1 = net.createServer (function (client) {client.write ('Hello World!\ r\ n'); server1.listen (9000) / /-var WebSocketServer = require ('ws') .Server, wss = new WebSocketServer ({port: 8181}); wss.on (' connection', function (ws) {console.log ('client connected'); ws.on (' message', function (message) {console.log (message)) }); summarize

Return to the directory

Browser compatibility

Server-Sent Events supports Chrome9+, Firefox6+, Opera11+, Safari5+

Server load

Server-Sent Events works in many ways, unless Server-Sent Events does not have to close the connection after each response.

WebSockets, the server only needs one process to handle all requests, there is no loop, and there is no need to allocate cpu and memory for each client.

Client load

Server-Sent Events uses the built-in implementation of the browser and costs only a small portion of the resources.

Like Server-Sent Events, WebSockets uses the built-in implementation of the browser and costs only a small portion of the resources.

Timeline

The default delay of Server-Sent Events is 3 seconds, but it can be adjusted.

Real real-time WebSockets

Implementation complexity

Server-Sent Events is even simpler than Long-polling.

WebSockets requires a WebSockets server to handle events and open a port

This is how the html5 server shared by Xiaobian pushes Server-sent Events and websocket. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are welcome to follow 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

Internet Technology

Wechat

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

12
Report