Real-time web and websocket practices

Source: Internet
Author: User
Tags event listener

Absrtact: Real-time web is becoming more and more important, and Google, Facebook and other big companies are gradually beginning 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 with the previous server push technology, WebSocket has a huge advantage, because WebSocket is full-duplex, not HTTP-based, once the connection is established will not be broken. 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 is completed between the server and the client, 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 group, which describes WebSocket:

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:

4 Safari >= 5 iOS >= 4.2 Firefox >= 4* 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:

// 建立连接socket.onopen = function(){ /* ... */ }// 通过连接发送了一些新数据socket.onmessage = function(data){ /* ... */ }// 关闭连接socket.onclose = function(){ /* ... */ }

The OnMessage event is triggered when the server sends some data, and the client can also call the Send () function to pass 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 ( Span class= "hljs-string" > "newdata-", msg); Socket.onopen=function ( "Why,hellothere").}; The messages sent and received only support string formatting. But it's easy to convert between strings and json data, so you can create your own protocol: varrpc={test:function (arg1,arg2) {/*...*/}};socket.onmessage=function (data) {//parse 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":[1,2]}

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 that when we instantiate a websocket, we use the WebSocket-specific protocol prefix ws://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.
Speaking of 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. The
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 some 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 is selected from the "MVC-based JavaScript Web rich application Development", click this link can be viewed from the blog point of view website.
                       
                     
Want to get more good articles in time, you can search "blog point of View" or scan the QR code below and follow.
                        

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.