Talk about the WebSocket introduction, and the difference between the socket

Source: Internet
Author: User
Tags server port

This topic should be the frequency of the interview is relatively high bar .... However, it is necessary to have a deeper understanding of the relationship between the two. Don't say much nonsense, direct into the question:

WebSocket Introduction and Principle Purpose: Instant messaging, alternate polling

The Instant Messenger on the website is very common, such as the QQ of the webpage, chat system and so on. In accordance with the technical capabilities of the past is usually the use of polling, comet technology solution.

The HTTP protocol is a non-persistent, one-way network protocol that allows the server to return data only after a connection has been made to allow the browser to make a request to the server. When instant messaging is required, by polling at a specific time interval (for example, 1 seconds), the browser sends a request to the server and then returns the latest data to the browser. The most obvious disadvantage of such a method is the need to constantly send requests, and usually the header of the HTTP request is very long, in order to transfer a very small amount of data to pay a huge price, it is very uneconomical, occupy a lot of broadband.

Disadvantage: can cause excessive unnecessary requests, waste traffic and server resources, every request, reply, wasted a certain amount of traffic on the same header information

However, the appearance of websocket can compensate for this shortcoming. In WebSocket, only the server and browser are required to perform a handshake through the HTTP protocol, and then a separate TCP communication channel is established to transmit the data.

Principle

WebSocket is an application-level protocol like HTTP, but it is a two-way communication protocol that is built on top of TCP.

Connection process-handshake process
    • 1. The browser, the server establishes the TCP connection, three times the handshake. This is the basis of communication, the Transmission control layer, if failure follow-up is not performed.
    • 2. After the TCP connection succeeds, the browser transmits information such as the WebSocket supported version number to the server via the HTTP protocol. (HTTP handshake before start)
    • 3. When the server receives a handshake request from the client, it also uses the HTTP protocol to reward the data.
    • 4. When a successful connection is received, the communication is transmitted over the TCP channel.
WebSocket the same point as the HTTP relationship
    • 1. It's all the same. TCP-based, both are reliability transport protocols.
    • 2. Both are application-level protocols.
Different points
    • 1. WebSocket is a two-way communication protocol that simulates the socket protocol and can send or receive information in both directions. HTTP is one-way.
    • 2. WebSocket is a handshake required to establish a connection.
Contact

WebSocket When a handshake is established, the data is transmitted over HTTP. However, after the establishment, the HTTP protocol is not required when the transmission is true.

The relationship between WebSocket and sockets

A socket is not a protocol, but a layer of abstraction for the convenience of using TCP or UDP, a set of interfaces between the application layer and the Transport control layer.

A socket is an intermediate software abstraction layer that the application layer communicates with the TCP/IP protocol family, which is a set of interfaces. In design mode, the socket is actually a façade mode, it is the complex TCP/IP protocol family hidden behind the socket interface, for the user, a set of simple interface is all, let the socket to organize data to meet the specified protocol.

When two hosts communicate, a socket connection is required, and the socket uses the TCP/IP protocol to establish a TCP connection. TCP connections are more dependent on the underlying IP protocol, and the connection to the IP protocol is dependent on the lower level of the link layer.

WebSocket is a typical application-layer protocol.

Difference

The socket is the Transport Control layer protocol, and WebSocket is the application layer protocol.

The relationship between HTML5 and WebSocket

The WebSocket API is part of the HTML5 standard, but this does not mean that WebSocket must be used in HTML or only in browser-based applications.

In fact, many languages, frameworks, and servers provide WebSocket support, such as:

    • * Based on C-libwebsocket.org
    • * Based on node. JS Socket.io
    • * Python-based Ws4py
    • * C + + based websocket++
    • * Apache support for WebSocket: Apache Module Mod_proxy_wstunnel
    • * Nginx support to WebSockets: Nginx as a WebSockets Proxy, Nginx announces supports for WebSocket Protocol, WebSocket proxying
    • * LIGHTTPD support for WebSocket: Mod_websocket
WebSocket mechanism

The following is a brief introduction to the principle and operating mechanism of WebSocket.

WebSocket is a new protocol for HTML5. It realizes the browser and the server full-duplex communication, can better save the server resources and bandwidth and achieve real-time communication, it is based on TCP, the same as HTTP through TCP to transfer data, but it and HTTP the maximum difference is:

    • WebSocket is a two-way communication protocol, after establishing the connection, both the WebSocket server and the Browser/client Agent can send or receive data to each other proactively, just like a Socket.
    • WebSocket requires a TCP-like client and server-side handshake connection to communicate with each other after a successful connection.

The non-WebSocket mode traditional HTTP client interacts with the server as shown:

Figure 1. Traditional HTTP Request Response Client Server interaction diagram

Using the WebSocket mode client interacts with the server such as:

Figure 2.WebSocket Request Response Client Server interaction diagram

Compared to the traditional HTTP each request-response requires the client and the server to establish a connection mode, WebSocket is similar to the Socket TCP Long connection communication mode, once the WebSocket connection is established, the subsequent data are transmitted in the form of a frame sequence. The client and the server are not required to re-initiate the connection request before the client disconnects the WebSocket connection or the servers end the connection. In the case of large amount of concurrency and high client-server interaction load, the consumption of network bandwidth resources is greatly saved, and the performance advantage is obvious, and the client sends and receives messages on the same persistent connection, and the real-time advantage is obvious.

We'll look at the difference between the WebSocket communication and the traditional HTTP via the client-side and service-end messages:

On the client side, new WebSocket instantiates a newer WebSocket client object that connects a server like Ws://yourdomain:port/path WebSocket url,websocket client object that is automatically parsed and recognized as The WebSocket request, thereby connecting the server port, performs both handshake processes, and the client sends data in a similar format:

Listing 1.WebSocket Client Connection messages
get/webfin/websocket/http/1.1Host:localhostUpgrade:websocketConnection:UpgradeSec- websocket-key:xqbt3imnzjbyqrinxeflkg==origin:http://localhost:8080

As you can see, the client-initiated WebSocket connection message is similar to the traditional HTTP message, and the "upgrade:websocket" parameter value indicates that this is a WebSocket type request, and "Sec-websocket-key" is WebSocket A base64 encoded ciphertext sent by the client requires the server to return a corresponding encrypted "sec-websocket-accept" answer, otherwise the client throws an "error during WebSocket handshake" fault and closes the connection.

The data format returned by the server after receiving the message is similar:

Listing 2.WebSocket Service-side response messages
http/1.1101  switching ProtocolsUpgrade:websocketConnection:UpgradeSec- websocket-accept:k7djldlooiwig/mopvwfb3y3fe8=

The value of "Sec-websocket-accept" is returned to the client after the server is computed with a client-consistent key, and "http/1.1 101 switching Protocols" indicates that the server accepts a client connection to the WebSocket protocol, After such a request-response processing, the client service side of the WebSocket connection handshake succeeds, the subsequent TCP communication can be made.

In terms of development, the WebSocket API is also very simple, we only need to instantiate the WebSocket, create the connection, and then the server and the client can send and respond to each other message, in the following WebSocket implementation and Case Analysis section, you can see the detailed WebSocket API and code implementation.

WebSocket implementation

As mentioned above, the implementation of WebSocket is divided into two parts of the client and the server, the client (usually the browser) sends the WebSocket connection request, the service side responds, implements the action similar to the TCP handshake, thus forms an HTTP between the browser client and the WebSocket server. Long connection Fast channel. The subsequent direct data transfer between the two is no longer necessary to initiate a connection and corresponding.

The following is a brief description of the WebSocket Server API and client API.

WebSocket Service-side API

The WebSocket server has been largely supported by the JEE JSR356 standard API in every major application server vendor, and the following is a list of some common commercial and open source application servers that support the WebSocket server side:

Table 1.WebSocket Service-side support
manufacturer Application Server Notes
Ibm Websphere WebSphere version 8.0 and above support, prior to 7.X with MQTT support similar HTTP long connection
Oracle Weblogic WebLogic 12c Support, 11g and 10g versions support similar HTTP long connections via HTTP Publish
Microsoft Iis IIS 7.0+ Support
Apache Tomcat Tomcat 7.0.5+ Support, 7.0.2X and 7.0.3X support via custom API
Jetty Jetty 7.0+ Support

Below we use the Tomcat7.0.5 version of the server-side sample code to illustrate the implementation of the WebSocket server:

The JSR356 WebSocket specification uses the javax.websocket.* API, which allows a common Java object (POJO) to use @ServerEndpoint annotations as the endpoint of the WebSocket server, with the following code examples:

Listing 3.WebSocket server-side API Example
@ServerEndpoint ("/echo")  Public classEchoendpoint {@OnOpen Public voidOnOpen (Session session) throws IOException {//The following code omits ...} @OnMessage Publicstring OnMessage (String message) {//The following code omits ...} @Message (MaxMessageSize=6)  Public voidReceiveMessage (String s) {//The following code omits ...} @OnError Public voidOnError (Throwable t) {//The following code omits ...} @OnClose Public voidOnClose (Session session, Closereason reason) {//The following code omits ... }   }

Code Explanation:

The simple code above establishes a WebSocket server, and the annotation annotation endpoint of the @ServerEndpoint ("/echo") indicates that the WebSocket server is running on the Ws://[server IP or domain name]:[serve R Port]/websockets/echo's access endpoint, the client browser has been able to initiate an HTTP long connection to the WebSocket client API.

A class that uses serverendpoint annotations must have a common parameterless constructor, and the Java method that @onMessage annotations is used to receive incoming WebSocket information, either in text format or in binary format.

OnOpen is called when a new connection is established at this endpoint. Parameters provide more detail at the other end of the connection. The Session indicates that the other end of the two WebSocket endpoint conversation connection can be understood as a concept similar to HTTPSession.

The OnClose is called when the connection is terminated. The parameter Closereason can encapsulate more details, such as why a WebSocket connection is off.

More advanced customizations such as @Message annotations, the MaxMessageSize property can be used to define the maximum message byte limit, and in the example program, if more than 6 bytes of information is received, the error is reported and the connection is closed.

Note: The WebSocket methods that are supported by different application servers in the early stages are not the same, even if the same vendor, different versions have subtle differences, such as the TOMCAT server 7.0.5 the above version is the standard JSR356 specification implementation, and the 7.0.2x/7.0.3x version uses the custom API ( Websocketservlet and Streaminbound, the former is a container used to initialize the WebSocket environment, which is used to specifically process WebSocket requests and responses, as described in the Case Analysis section, and tomcat7.0.3x and 7.0.2x The Createwebsocketinbound method is defined differently, adding a httpservletrequest parameter that allows more WebSocket client information to be obtained from the request parameter, as shown in the following code:

Listing 4.tomcat7.0.3x version WebSocket API
 Public classEchoservlet extends Websocketservlet {@Overrideprotectedstreaminbound createwebsocketinbound (String subprotocol,httpservletrequest request) {//the following code omits ....return NewMessageinbound () {//the following code omits ....}protected voidonbinarymessage (Bytebuffer buffer) throws IOException {//The following code omits ...}protected voidontextmessage (Charbuffer buffer) throws IOException {Getwsoutbound (). writetextmessage (buffer);//The following code omits ...}};}}

So choosing the Server side of WebSocket needs to choose its version, typically, the updated version of WebSocket support is the standard JSR specification API, but also to consider the development of ease of use and the old version of the program portability, and other aspects of the problem, as described in the following article of the customer case, This is because the client requires a unified Application Server version, so the Websocketservlet implementation of the Tomcat 7.0.3X version is used instead of the JSR356 @ServerEndpoint comment endpoint.

WebSocket Client API

For WebSocket clients, mainstream browsers (including PCs and mobile terminals) now support the standard HTML5 WebSocket API, which means that the client's WebSocket javascirpt scripts have good consistency and cross-platform features, and the following lists common Browser vendor support for WebSocket:

Table 2.WebSocket Client Support
Browser Support Situation
Chrome Chrome version 4+ support
Firefox Firefox version 5+ support
Ie IE version + + support
Safari IOS 5+ Support
Android Brower Android 4.5+ Support

The client WebSocket API is basically unified across mainstream browser vendors, so use the JavaScript API of the WebSocket client defined by the standard HTML5, and of course use the industry's open source framework that meets the WebSocket standard specification. such as Socket.io.

The following is a code example that illustrates the client implementation of WebSocket:

Listing 5.WebSocket Client API sample
var New WebSocket ("WS://   ws.onopen = function () {ws.send (" test!");};   = function (evt) {console.log (evt.data); Ws.close ();};   = function (evt) {console.log ("websocketclosed!");};   = function (evt) {console.log ("websocketerror!");};

The first line of code is to request a WebSocket object, the parameter is the server-side address that needs to be connected, as the HTTP protocol begins, the URL of the WebSocket protocol uses ws://, and the security WebSocket protocol starts with wss://.

The second line to the fifth behavior WebSocket object Registration Message handler function, WebSocket object support four messages OnOpen, OnMessage, OnClose and OnError, with these 4 events, we can easily and easily navigate Websock Et.

When the Browser and Websocketserver connection succeeds, the OnOpen message is triggered, and if the connection fails, the sending, receiving data fails, or the processing data is faulty, Browser triggers the onerror message; when Browser receives WebSocketS The onmessage message is triggered when the data is sent by erver, and the parameter evt contains the data transmitted by the Server, and the OnClose message is triggered when Browser receives a close connection request sent by the Websocketserver side. We can see that all operations are triggered in the form of an asynchronous callback, which does not block the UI, allows for faster response times, and a better user experience.

Talk about the WebSocket introduction, and the difference between the socket

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.