Preliminary study on Html5-websocket

Source: Internet
Author: User
Tags nodejs websocket

The HTML5 specification has brought us many new features on the basis of traditional web interaction, and these new features have been popularized and used as Web technology is widely used in web app development, and WebSocket as a new web communication technology is of great significance.

What is a socket? What is WebSocket? What is the difference between the two? WebSocket is the implementation of just porting the socket concept to the browser?

We know that two applications (processes) in the network need to communicate with each other at full duplex (that is, both sides can send messages to each other at the same time), the socket is needed, it can provide end-to-end communication, and for programmers, He just needs to create a socket instance at one end of an application (called a client) and provide the IP address and port it wants to connect to one end (called the server), while the other end (the server) creates another socket and binds the port to listen. Then the client connects to the server, the server accepts the connection, the two sides establish an end-to-end TCP connection, the connection can be two-way communication, and once the connection is established, there is no client service side of the communication between the two sides, providing the end-to-end communication. We can use this approach to build a desktop version of the IM program that allows users on different hosts to send messages. In essence, a socket is not a new protocol, it is simply a encapsulation of the TCP/IP protocol family communication mechanism in order to facilitate the programmer's network programming.

WebSocket is a part of the HTML5 specification, which draws on the idea of sockets, providing a full-duplex communication mechanism between the Web application client and the server side (note that the client service side). At the same time, it is a new application layer protocol, the WebSocket protocol is designed to provide a Web application and service-side full-duplex communication and a special application layer protocol, which is usually expressed as: Ws://echo.websocket.org/?encoding=text http/1.1, you can see that in addition to the previous protocol name and HTTP, its representation address is the traditional URL address.

As you can see, websocket is not simply porting the concept of sockets in a browser environment, and this article will go through a small demo to further explain the difference between the socket and the websocket in use.

The communication principle and mechanism of websocket

Since it is browser-based web technology, its communication must be http,websocket itself, although it is also a new application layer protocol, but it can not be separated from HTTP and exist alone. Specifically, we build a WebSocket instance on the client and bind it to a server address that needs to be connected, and when the client connects to the service, it sends an HTTP message like the following to the service side

As you can see, this is an HTTP GET request message, note that there is a upgrade header in the message that tells the server that it needs to switch the communication protocol to WebSocket if the server supports WebSocket protocol, Then it switches its communication protocol to WebSocket and sends a response message header similar to the following for the client

The returned status code is 101, which means that the client protocol conversion request is agreed upon and converted to the WebSocket protocol. The above process is done using HTTP communication, called the WebSocket Protocol handshake (WebSocket Protocol handshake), after the handshake, the client and the server to establish a websocket connection, The future of communication is the WebSocket agreement. So summing up the WebSocket handshake requires the use of the HTTP protocol to establish the connection after the communication process using the WebSocket protocol . It is also necessary to understand whether the WebSocket connection is based on the TCP connection that we just initiated the HTTP connection. Once the connection is established, we can transfer data, WebSocket provides two kinds of data transfer: Text data and binary data.

Based on the above analysis, we can see that websocket can provide low-latency, high-performance client-to-server bidirectional data communication. It overturns the request processing response pattern of the previous Web development, and provides a real client request, the server pushes the data pattern, especially suitable for real-time data interactive application development.

Before WebSocket, what are the ways we use the web to get real-time data interaction?

1) How to poll regularly:

The client continuously sends requests to the server at a certain time interval, requesting the latest data from the server and then updating the client display. This approach actually wastes a lot of traffic and creates a lot of pressure on the service side.

2) Comet technology

Comet is not a new communication technology, it is a hack technology on the client request server, usually it is divided into the following two kinds of practices

(1) service-side push technology based on long polling

Specifically, the client first sends a request to the server, and the server receives the request and does not immediately return if the data is not updated, the server blocks the return of the request until the data has been updated or a connection time-out occurs, and the client sends the same request again after the server returns the data, as follows:

2) long connection based on streaming data

It is common practice to embed a hidden iframe in the page and then have the SRC attribute of the IFRAME point to a server-side address of our request, and for data updates, we encapsulate the data update operation on the page as a JS function, passing the function name as a parameter to the address.

After the service side receives the request resolves the address takes out the parameter (the client JS function call name), whenever has the data update, returns to the client function the call, and will be with the new data with the JS function's parameter to fill in the return content, for example returns " <script type="text/javascript">update("data")</script> " such a string, means calling the client update function with the data parameter for client view updates. The basic model is as follows:

You can see that comet technology is a real-time, new technology for server-side push data that is simulated for the client pull response model. And because browser compatibility cannot be widely used.

Of course, this is not to say that these techniques are useless, even if websocket has been proposed and implemented as a specification, but for older browsers, we still need to downgrade it to the above ways to achieve real-time interaction and server-side data push.

To this end, we understand the principle of websocket, the following through a simple chat application to deepen the understanding of websocket again.

The app needs to be simple to open two Web pages in a web tab and simulate two web-client implementations of chat capabilities.

The first is the client as follows:

Client.html

<!DOCTYPE HTML><HTML><HeadLang= "en">    <MetaCharSet= "UTF-8">    <title></title>    <style>        *{margin:0;padding:0;        }. Message{width:60%;margin:0 10px;Display:Inline-block;text-align:Center;Height:40px;Line-height:40px;font-size:20px;Border-radius:5px;Border:1px solid #B3D33F;        }. Form{width:100%;position:fixed;Bottom:300px; Left:0;        }. Connect{Height:40px;vertical-align:Top;            /*padding:0;*/width:80px;font-size:20px;Border-radius:5px;Border:None;background:#B3D33F;Color:#fff;        }    </style></Head><Body><ulID= "Content"></ul><formclass= "form"><inputtype= "text"placeholder= "Please enter the message sent"class= "message"ID= "message"/><inputtype= "button"value= "Send"ID= "Send"class= "Connect"/><inputtype= "button"value= "Connection"ID= "Connect"class= "Connect"/></form><Script></Script></Body></HTML>

Client JS Code

  varOul=document.getelementbyid (' content '); varOconnect=document.getelementbyid (' Connect '); varOsend=document.getelementbyid (' Send '); varOinput=document.getelementbyid (' message ')); varWs=NULL; Oconnect.onclick=function() {ws=NewWebSocket (' ws://localhost:5000 '); Ws.onopen=function() {oul.innerhtml+ = "<li> Client connected </li>"; } ws.onmessage=function(evt) {oul.innerhtml+ = "<li>" +evt.data+ "</li>"; } ws.onclose=function() {oul.innerhtml+ = "<li> Client disconnected </li>";        }; Ws.onerror=function(evt) {oul.innerhtml+ = "<li>" +evt.data+ "</li>";    };    }; Osend.onclick=function(){        if(WS) {ws.send (oinput.value); }    }

Here is the native API for the HTML5 WebSocket API, which is simple to use new websocket to create a WS instance that specifies the connection server address, and then register the OnOpen (connection server) for that instance. OnMessage (accepts server-side data), OnClose (closes the connection), and Ws.send (after the connection is established) sends the request. It says so much, in fact you can see the HTML5 WebSocket API itself is a very simple object and its several methods only.

The service side uses Nodejs, which is based on a nodejs-websocket Nodejs server-side library, which is a lightweight implementation of the Nodejs WebSocket servers, and is actually written using the net module provided by Nodejs.

Server.js

varApp=require (' http '). Createserver (handler);varWs=require (' Nodejs-websocket ');varFs=require (' FS '); App.listen (80);functionHandler (req,res) {fs.readfile (__dirname+ '/client.html ',function(err,data) {if(Err) {Res.writehead (500); returnRes.end (' ERROR '); } res.writehead (200);    Res.end (data); });}varServer=ws.createserver (function(conn) {Console.log (' New Conneciton '); Conn.on ("Text",function(str) {broadcast (SERVER,STR);    }); Conn.on ("Close",function(Code,reason) {Console.log (' Connection closed '); }). Listen (5000);functionBroadcast (server, msg) {Server.connections.forEach (function(conn) {Conn.sendtext (msg); })}

First, the HTTP module listens to the user's HTTP request and displays the Client.html interface, then creates a websocket server to wait for the user to connect and broadcast it to all connected clients after receiving the data sent by the user.

Below we open two browser tabs to simulate two clients to connect,

Client One connection:

The request response message is as follows:

We can see this handshake as we said before,

Client two connection process and 1 is the same, here in order to see we use the FF browser, two clients connect the following situation:

The message is sent as follows:

As you can see, the messages sent by both sides are broadcast by the server to each and every client connected to it.

From the above we can see, in order to do a point-to-point IM application, websocket to do is to let all clients connect to the server, the servers send different clients to their own messages forwarded or broadcast, and for the original socket, as long as the two ends of the connection, Can send end-to-end data, do not need to go through a third-party forwarding, which is websocket different from the socket is an important feature.

Finally, in order to illustrate the HTML5 specification in the WebSocket in the client with the native API, the actual development, there are more famous two libraries Socket.io and SOCKJS, they are the original API has been further encapsulated, providing more features, are divided into the client and the service side of the implementation, in practical applications, you can choose to use.

Preliminary study on Html5-websocket

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.