Web socket and Web worker basic principles and usage

Source: Internet
Author: User

Personally, the two most attractive features of HTML5, web sockets and workers provide a new reference for building high-performance Web applications.

In general, Web sockets provide more efficient transport protocols, and Web workers provide multithreading to improve the computational efficiency of Web applications. Recent projects have been useful, corresponding to the resolution of two problems, the current operation effect is very good.

Here is a summary of the basic principles of these two technologies, and common APIs. Memo, also lists key mastery points, getting started and the basics used enough.

Web Socket

WebSocket is a protocol, essentially the same as http,tcp. The protocol is used to describe how the data is transmitted. Its URL prefix is ws://or wss://, which is encrypted. The way the client and the server interact WebSocket are also understood as "HTTP handshake +tcp data transfer."

HTTP Handshake +tcp Data transfer:

  1. Browsers (browsers that support WebSocket), like HTTP, initiate a request and wait for a response from the server;

  2. The server returns the handshake response, telling the browser to transmit the subsequent data in accordance with the WebSocket data format;

  3. The browser and the server socket connection is not interrupted, at this time this connection and HTTP is different is it is duplex;

  4. Use this long connection for data transfer when the browser and server have any data that needs to be passed

This is said to be the HTTP handshake , because the browser and server in the establishment of long-connected handshake process is in accordance with HTTP1.1 protocol sent, there are request,request header, Response, Response header. But the difference is that the field inside the header has a specific meaning.

Said it is a TCP transmission , mainly reflected in the establishment of a long connection, the browser can send data to the server, the server can also send a request to the browser. Of course, its data format is not its own definition, is the data to be transmitted in the outer layer has the WS protocol of the outer package.

Data transfer process

websocket data transfer is in frame form, For example, a message will be divided into several frames, in order to transfer out. There are several benefits to doing so:

    1. same as HTTP chunk , the data side can be generated to deliver the message, that is, to improve transmission efficiency.

Client API

Here is the API for using WebSocket on the client, syntax is the basic JavaScript, very simple. Only the server-side API, there are a variety of web framework support, such as play, can be self-search.

var socket; $ ("#connect"). Click (Function (Event) {    socket = new  WebSocket ("Ws://127.0.0.1:8999/getlog");      socket.onopen = function () {         console.log ("socket has been opened");     }     socket.onmessage = function (msg) {         console.log ("get log: "  + msg.data);     }     socket.onclose = function ()  {         alert ("socket has been closed");    }         ws.onerror = function ()  {         console.log ("web socket error!");     });  $ ("#send"). Click (Function (event) {  &NBSp; socket.send ("Send from client");});  $ ("#close"). Click (Function (event) {    socket.close ();})
Web worker

When you execute a script in an HTML page, the state of the page is not responsive until the script is complete.

Web Worker is a JavaScript running in the background, independent of other scripts, without affecting the performance of the page. You can continue to do anything you want to do: Click, select Content, and so on, while the Web worker runs in the background.

In addition to DOM operations, in theory any JS Script task can be put into the worker, syntax restrictions, it is not cross-domain access JS. Workers are often used for complex computations that require a significant amount of time and CPU resources, in exchange for a friendly user-friendliness of the foreground, or, in other words, improved service performance from a user experience perspective.

Api

A message is sent between the worker's main thread and the child thread through PostMessage (), and the received message is obtained by adding a "onmessage" event listener to the Web worker.

When we create a Web worker object, it continues to listen for messages, even after the external script finishes, until it is terminated. To terminate the Web worker and release the browser/computer resources, use the Terminate () method.

var worker =new worker ("Worker_job.js");     Creates a worker object and passes it the URL of the script that will execute in the new thread worker.postmessage ("Hello World");              Send data to worker Worker.onmessage =function (evt) {///Receive data function passed by worker Console.log (Evt.data); Output data sent by worker}

Web socket and Web worker basic principles and usage

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.