The concrete implementation method of WebSocket long connection in HTML5

Source: Internet
Author: User

In HTML5, the Web Socket APIassociated with data communication is invoked to enable the push of information from the server to the client.
Socket, also known as socket, is a technology that develops two-way communication in a TCP interface based on the standard. Typically, the socket is used to describe the IP address and port, which is a character handle in the communication process. When the server side and multiple application services bind a socket, the different ports correspond to different application service functions through the character handle in the communication. Currently, most browsers support the operation of the socket API in HTML5.

WebSocket connection server and client, this link is a real-time long connection , once the server side with the client to establish a two-way link, you can push the data into the socket, the client as long as there is a socket bound address and port to establish contact with the server, You can receive the data that is pushed.

The use of the WebSocket API is divided into the following steps:

Step 1, create a connection , a new WebSocket object is very convenient, the code is as follows:
var host = "ws://echo.websocket.org/";
var socket=new WebSocket (host);
Note: TheURL must start with a "ws" Character , and the remainder can be written as an HTTP address. The address is not written using the HTTP protocol because its properties are WebSocket URLs; The URL must consist of 4 parts, namely the Communication token (WS), the hostname (host), the port number (port), and the WebSocket Server.

Step 2, send the data. when the WebSocket object is connected to the server, send the data using the following code:
Socket.send (Datainfo);
Note: Where objWS is the newly created WebSocket object, the Datainfo parameter in the Send () method is a character type, which is a data format that can only use text data or convert a JSON object to text content.

Step 3, receive the data. the client adds an event mechanism to receive the data sent by the server, with the following code:
Socket.onmessage=function (event) {
Pop-up information received
alert (event.data);
Other code
}

The "data" property of the event object in the callback function is used to obtain the content sent by the server side, which can be a string or a JSON object.

Step 4 status flag. The status value during the connection is recorded by the ReadyState property of the WebSocket object.
The "ReadyState" property is a status flag for a connection that gets the state of the WebSocket object when it is connected, opened, changed, and closed. The status flag has a total of 4 property values, as shown in the following table:


————————————————————————————————————
Property Value Property Constant description
————————————————————————————————————
0 connecting connection not yet established
1 OPEN WebSocket links have been established
2 CLOSING connection is shutting down
3 CLOSED connection is turned off or not available
————————————————————————————————————

WebSocket object During the connection process, by detecting the change of the status flag, we can get the state of the server-side connection with the client and return the status code form to the client.

Step 5 Close the socket connection.

Socket.close ();

WebSocket can be seen as an HTTP protocol in order to support the long connection of a large patch, it and HTTP have some commonality, is to solve some problems that HTTP itself can not solve a modified design. In the previous HTTP protocol, the so-called keep-alive connection refers to the completion of multiple HTTP requests in a single TCP connection, but it is still a separate header for each request, and the so-called polling is the proactive sending of the server from the client (typically the browser) HTTP Request query whether there is new data. The two models have a common disadvantage,In addition to the real data part, the server and the client also need to exchange a large number of HTTP headers, information exchange efficiency is very low。 They establish a "long connection" that is pseudo. Long connections, but the benefit is that you do not need to modify the existing HTTP server and browser architecture to be implemented.

The first problem that WebSocket solves is that after a TCP connection is established through the first HTTP request, no more HTTP request is required for subsequent exchange data, making the long connection a true long connection. However, there is no need to send HTTP headers to Exchange data, which is obviously different from the original HTTP protocol, so it needs to be upgraded for both the server and the client. On this basisWebSocket is also a dual-channel connection,you can either send or receive information on the same TCP connection。 There are also multiplexing functions, and several different URIs can be reused for the same WebSocket connection. These are the original HTTP can not do.

Also say a little technical detail, because see someone ask WebSocket may enter some kind of half-dead state. This is actually some flawed design of the original network world. The WebSocket is true. Long connections solve both the server and the client side of the problem, but the pit is the network application in addition to the server and the client, another huge presence is the middle of the network link. A http/websocket connection often has to go through countless routes, firewalls. You think your data is sent in a "connection", in fact, it will cross the mountains and rivers, after countless times of forwarding, filtering, in order to finally reach the end. In this process, the processing of intermediate nodes is likely to surprise you.

For example, the middle nodes of these pits may think that a connection is useless without data sending for a period of time, and they will cut off these connections on their own. In this case, regardless of the server or the client will not receive any prompt, they will only wishful thinking that the red line between each other, in vain side by side to send the information can not reach the other shore. In the implementation of the computer network protocol stack There will be a layer of cache, unless you fill these caches, your program will not find any errors. In this way, it would have been a wonderful WebSocket long connection, which might be ininto a half-dead state without knowing it.

And the solution, WebSocket designers have already thought. It isenables servers and clients to send Ping/pong Frame(RFC 6455-the WebSocket Protocol). ThisFrameis a special kind of packet that contains only some metadata without the need for a real data Payload, and can maintain the connectivity of the intermediate network without affecting the application

The concrete implementation method of WebSocket long connection in HTML5

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.