Websockets everywhere with socket. Io

Source: Internet
Author: User

Recently, a young man complained that Ajax was weak and could not achieve persistent connections. Then he kept crying .... in fact, this may not be implemented. For long links, comet and server push rely on the server. If the server implements server push, it is easy to say that, I understand that most servers currently support Apache, Jetty, fast CGI, and ninix (re-add nginx_http_push_module to compile), but this is often not enough... well, this is not good. I have translated a socket. io. JSArticleThis section describes in detail how to use ajax to maintain HTTP persistent connections and how to implement socket. io (that is, to implement websockets In the compatible version). It also involves node. js (Google)

Http://howtonode.org/websockets-socketio

---- Reprinted, please specify the author information ifree

 

Body:

If you have been working on real-time network applications, you may have learned some different technologies to improve data interaction latency between the server and client over the past few years. if you are developing a multiplayer game, a chat system or an application that requires frequent short-term interaction with services as frequently as Twitter, you may want to 'invert 'the traditional interaction model. therefore, it is better to have the server send data to you than send a request to the server.

Today, when we develop a system similar to real-time, we always think of persistent connections, and comet certainly has websocket. however, they have their own limitations. For example, server implementation is different, there are too many restrictions, and browser support is not enough...

Below is mySocket. Io segmentCode:

 
VaR socket = new IO. socket (); socket. On ('connect ', function () {// connected !}); Socket. On ('message', function (MSG) {// message coming}); socket. Send ('Hello world! ');

If you are familiar with websocket (not familiar with Apis), the main purpose is to simplify the two-way HTTP protocol. you will find that they are very similar. but the difference is (because the browser has not yet fully implemented HTML5) socket. i/O supports IE6-9, Firefox 3-4, Safari 3-5, chrome 3-6, IOs (iPhone, iPad) and other compatible browsers.

 

Review current real-time network implementation

In this age, a majority of Web developers were using Ajax to implement real-time interaction (Asynchronous interaction), just likeSimilar to socket. Io. some third-party JS libraries, such as jquery, encapsulate Ajax objects with better compatibility to achieve asynchronous request functions.

For example, if you want to request resources from the server in real time, you may do the following:

 

 
Setinterval (function () {$. ajax ({URL: '/My/page', success: function (data) {// do something with the data});}, 5000 );

In this way, data is retrieved from the server every five seconds. In my opinion, this is almost as efficient as rfc1149 (IP datagram) standards.

You may also reduce the waiting time:

 

Setinterval (function () {$. ajax ({URL: '/My/page', success: function (data) {// do something with the data});}, 100 );

However, you may ignore the following two points:

    • HTTP latency. A packet may consume 200 ms for round-trip in a high-speed network, but this is not always the case. If it is 500 or higher, it is sometimes unnecessary because:
    • The server may not have the data we need, which leads to a lot of unnecessary bandwidth waste.

 

Long polling

The traditional round-robin method is to continuously request data from the server. To overcome its disadvantages, it is necessary to maintain a persistent connection when the server does not have data. this dramatically reduces network latency (persistent connections). Therefore, this is also a server push technology.

 

 
Function load () {$. ajax ({URL: '/My/page', success: function () {// do something with the data}, complete: load, timeout: 20000 });}

 

 

How to achieve persistent connection

If you are from a more traditional software development industry (such as desktop software), you may wonder why we don't keep persistent connections.

There may be two ways to implement it in a browser:

    • XMLHttpRequest andMultipart/X-mixed-replaceMime Type (that is, the XMLHTTP instance that sets multipart to true in the xhr request );

Although netsacpe introduced this technology as early as 1995 (but not for all browsers), it is only widely supported in Firefox.

    • Use<IFRAME>Header meta information settingsTransfer-encoding: chunkedAndConnection: keep-alive.

In this way, you can create the <SCRIPT> tag, dynamically execute the script, and refresh the IFRAME internally to keep the parent window from refreshing. This can also be seen as a server push method.

However, the endless progress bar appears below the browser, which seriously damages the user experience. In the IE environment, you can <IFRAME>Put it in a hidden Document Object (htmlfile object created using ActiveX Object). Gtalk implementation in Gmail uses this technology, which is analyzed/discovered by Alex Russell.

Now, it is obvious that these technologies play a role in a certain environment, but the most fundamental thing is that the current server has different request methods:

    • Request Header Information (Content-Type, connection ...).
    • Persistent connections (this requires long polling, but not full support ).
    • Framework information. For multipart, each message must be separated by the '-----' delimiter for parsing. (Yes, the data of each request is separated by '----------'. See the request data ).
    • Browser quirks (for example, ie requires some NULL bytes to identify each piece of data in the request ).

All this is done to minimize data latency, but we usually only use XMLHttpRequest as a good solution for data transmission on the server.

 

General Solutions

With websocket, "a dual-end interaction dedicated to BS architecture does not rely on 'Multiple HTTP connection'", as Hickson said.

Websocket utilizes the advantages of the HTTP/1.1 standard. It can be said that this is a brand new Protocol: (interested in RFC)

 

 
The upgrade general-header allows the client to specify what additional communication protocols it supports and wowould like to use if the server finds it appropriate to switch protocols. examples: HTTP/2.0, shttp/1.3, IRC/6.9, RTA/x11http: // www.w3.org/protocols/rfc2616/rfc2616-sec14.html

 

 

Websocket does not close the connection when sending and receiving messages. Apart from its own security model (based on the UTF-8 encoding framework), it can be called "Web-based TCP ".

However, websocket still has some problems:

    • The server must process websocket requests separately and execute the websocket-specific handshake protocol and websocket protocol.
    • No extensive browser support.

 

Use node. js

Node. js brings a unique and exciting feature to developers: You can use the most popular scripting technology to write your non-blocking web server.

Like this:

HTTP. createserver (function (request, response) {setTimeout (function () {response. writehead (200, {'content-type': 'text/plain '}); response. end ('Hello world \ n') ;}, 20000 );}). listen (0, 8124 );

 

Although this simple API is available, it is difficult for you to continue to enhance yourProgramBut socket. io-node can provide an auxiliary implementation. The following is a chat program of about 10 lines, and supports Server broadcast:

 

VaR buffer = []; Io. on ('connection', function (client) {client. send ({Buffer: Buffer}); client. broadcast ({announcement: client. sessionid + 'connected'}); client. on ('message', function (Message) {var MSG = {message: [client. sessionid, message]}; buffer. push (MSG); If (buffer. length> 15) buffer. shift (); client. broadcast (MSG) ;}); client. on ('disconnect', function () {client. broadcast ({announcement: client. sessionid + 'disconnected '});});});

The best thing is that during browsing, it will process your persistent connections, flash socket, IFRAME requests.

 

Further reading

If You Want To further study socket. io, you can go to git the source code of repositories can be further studied. You can also take a look at several items (Note: node. JS is a high-performance WEB server based on the v8js engine. It's great to have time to read it.)

    • http://github.com/substack/dnode
    • http://github.com/jacobthornton/space-tweet
    • http://github.com/mkilling/alfamegle
    • http://github.com/deserat/sock-drawer/
    • http://github.com/gerad/lazeroids-node/

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.