Real-time web and websocket practices

Source: Internet
Author: User

Introduction: Real-time web is becoming more and more important, Google, Facebook and other large companies have gradually started to provide real-time services. Real-time web will be one of the hottest topics of the future.
This article is selected from the MVC-based JavaScript Web rich application development.

Why is real-time web so important? We live in a real-time (real-time) world, so the ultimate natural state of the web should also be real-time. Users need real-time communication, data, and search. Our demand for real-time information on the Internet is becoming more and more demanding, and it is unbearable if messages or messages are updated only a few minutes later. Many big companies, such as Google, Facebook, and Twitter, are now focusing on the real-time web and providing real-time services. Real-time web will be one of the hottest topics of the future.

The development history of real-time web

The traditional web is an HTTP-based request/response model: The client requests a new page, the server sends the content to the client, and the client requests another page to resend the request. Later it was suggested that Ajax,ajax makes the page experience more "dynamic" and can initiate requests to the server in the background. However, if the server has more data to push to the client, it is not possible to directly send data from the server to the client after the page is loaded. Real-time data cannot be "pushed" to the client.
In order to solve this problem, a lot of solutions have been proposed. The simplest (violent) scenario is polling: every once in a while, new data is requested from the server. This makes the user feel that the app is real-time. This can actually cause delays and performance problems because the server processes a large number of connection requests per second, each with a TCP three handshake and a header message with HTTP. Although many applications are still using polling, this is not the ideal solution.
Later, with the advent of comet technology, there are many more advanced solutions. These technical solutions include permanent frames (forever frame), xhr streams (xhr-multipart), Htmlfile, and long polling. Long polling means that the client initiates a XHR connection to the server, which never shuts down, and the connection is always suspended for the client. When the server has new data, the response is sent to the client in a timely manner, and then the connection is closed. Then the entire process is repeated and the server push is implemented in this way.
Comet technology is a non-standard hack technology, and because of this, browser-side compatibility becomes a problem. First, performance issues cannot be resolved, and each connection to the server has full HTTP header information, which can be a tricky issue if your application requires a very low latency. Of course not that comet itself is problematic, because there are no alternatives before comet is our only option.
Browser plugins (such as Flash) and Java are also used to implement server push. They can establish a socket connection directly to the server based on TCP, which is ideal for pushing real-time data to the client. The problem is that not all browsers have these plugins installed, and they are often blocked by firewalls, especially in the corporate network.
Now the HTML5 specification prepares an alternative for us. But this specification is a little bit ahead, many browsers are not supported, especially IE, for many developers today is not very helpful, given that most browsers have not yet implemented HTML5 WebSocket, the best way is still to use comet.

WebSocket

WebSocket (http://dev.w3.org/html5/websockets) is part of the HTML5 specification (HTTP://WWW.W3.ORG/TR/HTML5), which provides a two-way, TCP-based, Full-duplex socket connection. This means that the server can push data directly to the client, without the need for developers to resort to long polling or plug-ins to do so, which is a big step forward. Although some browsers implement WebSocket, the Protocol (Http://goo.gl/F7lvW) is still being revised because some security issues are not resolved. However, this will not hinder our pace, these security issues are technical issues, will soon be repaired, WebSocket will soon become the final specification. At the same time, for browsers that do not support websocket, you can downgrade the use of stupid methods, such as comet or polling.  .
compared to previous server push technology, WebSocket has a huge advantage, because WebSocket is full-duplex, not HTTP-based, and will not be broken once a connection is established. The real problem with comet is that HTTP is too bulky for each request to have full HTTP header information. And it contains a lot of useless TCP handshakes, because HTTP is a higher-level network protocol than TCP.  
When using websocket, once the handshake between the server and the client is complete, the information can be freely exchanged to both ends without attaching the useless HTTP header information. This greatly reduces the bandwidth footprint and improves performance. Because the connection is active, the server can be sent to the client as soon as the new data is updated (no client requests first, the server responds). In addition, the connection is duplex, so the client can also send the data to the server, of course, there is no need to attach extra HTTP headers.  
The following is a statement from Google's Ian Hickson,html5 spec team head, which describes WebSocket as follows:

Reduce kilobytes of data to 2 bytes ... and the delay from 150 milliseconds to 50 milliseconds, this optimization across more than one magnitude, in fact, only the two-point optimization is enough to make Google convinced that WebSocket will bring the product a non-general user experience.

Now let's see which browsers support WebSocket:

Chrome >= 4 Safari >= 5 IOS >= 4.2 Firefox >= Opera >= 11*

Although both Firefox and Opera are websocket, it is not enabled by default, given that WebSocket still has security implications. But that's not a big deal, and perhaps the WebSocket security issue has been solved when the book is published. You can also downgrade in browsers that do not support websocket, using dumb methods like Comet and Flash.
Detecting whether the browser supports WebSocket is also very simple and straightforward:

Varsupported= ("WebSocket" Inwindow), if (supported) alert ("websocketsaresupported");

In the long run, the browser's WebSocket API is very clear and logical. You can use the WebSocket class to instantiate a new socket (socket), which requires the end address of the incoming server, which in this case is ws://example.com:

var socket = new WebSocket ("ws://example.com");

Then we need to add an event listener to this socket:

Establish connection Socket.onopen = function () {/* ... */}//send some new data through the connection Socket.onmessage = function (data) {/* ... */}//close connection SOCKET.O Nclose = function () {/* ... */}

When the server sends some data, the OnMessage event is triggered, and the client can also call the Send () function to return the data back to the server. Obviously, we should call it after the connection is established and the OnOpen event is triggered:

socket.onmessage=function (msg) {    console.log ("newdata-", msg);}; Socket.onopen=function () {    socket.send ("Why,hellothere").}; The messages sent and received only support string formatting. But between string and JSON data can be easily converted to each other, so that you can create your own protocol: varrpc={    test:function (ARG1,ARG2) {/*...*/}}; Socket.onmessage=function (data) {    //parsing json    varmsg=json.parse (data );     //Call RPC function     rpc[msg.method].apply (Rpc,msg.args);}; 

In this code, we create a remote procedure call (REMOTEPROCEDURECALL,RPC) script that the server can send some simple JSON to invoke the client's function, just like this line of code:

{"Method": "Test", "args": [+]}

Note that the call here is confined to the RPC object. The reason for this is primarily for security reasons, and if arbitrary JavaScript code is allowed to be executed on the client, the hacker will exploit the vulnerability. You can call the close () function to close the connection:

Varsocket=newwebsocket ("Ws://localhost:8000/server");

You must have noticed. We used the WebSocket-specific protocol prefix ws://when instantiating a websocket instead of http://. WebSocket also supports encrypted connections, which requires TLS with wss://as the protocol prefix. By default, WebSocket uses port 80 to establish a non-encrypted connection, using 443 ports to establish an encrypted connection. You can override the default configuration by bringing a custom port to the URL. Keep in mind that not all ports can be used by clients, and some unconventional ports are easily blocked by firewalls.
Now, you might think, "I can't use websocket in my project, because the standards are not yet formed, and IE doesn't support websocket." The idea is not wrong, fortunately, we have a solution. Web-socket-js is a websocket based on the Adobeflash implementation. Use this library to gracefully downgrade in browsers that do not support websocket. After all, almost all browsers have Flash plugins installed. The SOCKETAPI and HTML5 standard specifications based on the flash implementation are exactly the same, so when WebSocket's browser compatibility is better, simply remove the library without having to make any changes to the code.
Although the client's API is very concise and straightforward, the server-side situation is different. The WebSocket agreement contains two mutually incompatible draft agreements: draft 75 and draft 76. The server needs to determine which draft protocol to use by detecting the type of connection handshake used by the client.
WebSocket first initiates an HTTP "Upgrade" (upgrade) request to the server. If your server supports WebSocket, the WebSocket handshake is performed and a connection is initialized. The upgrade request contains information about the original domain (the domain name that the request was issued from). A client can establish a WebSocket connection to any domain name, and only the server will decide which clients can connect to it, and the common practice is to whitelist the domain name that is allowed to connect.
At the beginning of WebSocket's design, designers wanted to be able to live in harmony with firewalls and proxy software as long as the initial connection used the usual port and HTTP header fields. But the ideal is plump, the reality is the bone feeling. Some agent software has modified the header information of WebSocket's "Upgrade" request, breaking the protocol rules. In fact, the latest update to the draft Protocol (version 76) also inadvertently breaks down the compatibility of reverse proxies and gateways. To better and more successfully use WebSocket, here are a few steps:

    • Use a secure WebSocket connection (WSS). The proxy software does not tamper with encrypted connections, and the data you send is encrypted and not easily stolen by others.

    • Use a TCP load balancer in front of the WebSocket server instead of using an HTTP load balancer, unless an HTTP load balancer preaches itself to support WebSocket.

    • Do not assume that browsers support WebSocket, although browser support WebSocket is only a matter of time. Admittedly, if the connection cannot be established quickly, graceful demotion is quickly handled using comet and polling.

So, how do you choose a server-side solution? Fortunately, support for WebSocket is implemented in many languages, such as Ruby, Python, and Java. Again, verify that each implementation supports the latest version of the 76 protocol, as this Protocol is supported by most clients.

    • node. js

─node-websocket-server (Http://github.com/miksago/node-websocket-server)
─socket.io (Http://socket.io)

    • Ruby

─eventmachine (Http://github.com/igrigorik/em-websocket)
─cramp (Https://github.com/lifo/cramp)
─sunshowers (http://rainbows.rubyforge.org/sunshowers/)

    • Python

─twisted (Http://github.com/rlotun/txWebSocket)
─apachemodule (Http://code.google.com/p/pywebsocket)

    • Php

─php-websocket (Http://github.com/nicokaiser/php-websocket)

    • Java

─jetty (Http://www.eclipse.org/jetty)

    • Googlego

─native (Http://code.google.com/p/go)

This article has been selected from the MVC-based JavaScript Web rich application Development, click this link can be viewed on the website of the blog.  
650) this.width=650; "Src=" http://img.blog.csdn.net/20170110110130932?watermark/2/text/aHR0 cdovl2jsb2cuy3nkbi5uzxqvynjvywr2awv3mjawng==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70/gravity/ Southeast "alt=" Picture description "title=" "style=" Border:0px;vertical-align:middle;margin:auto; "/>

want to get more wonderful articles in time, search for "blog view" or scan the QR code below and follow.
650) this.width=650; "src=" http://img.blog.csdn.net/20161128135240324 "alt=" Picture description "title=" Picture description " Style= "Border:0px;vertical-align:middle;"/>


This article is from the blog of "Blog View blog", make sure to keep this source http://bvbroadview.blog.51cto.com/3227029/1890662

Real-time web and websocket practices

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.