WebSocket and node. js in perfect combination

Source: Internet
Author: User

The reason why I write this article is that I think the more simple the technology can often play the more important role, with the birth of a variety of new technologies, real-time web technology has come into our. WebSocket and node. js make it easy to develop real-time applications with very high performance.

About WebSocket

WebSocket is HTML5 important feature, it directly in the browser with the socket support, which gives the web development unlimited imagination, although there have been flash SOCKET+JS implementation, but after all, unstable, and compatibility has a lot of problems, Of course, the popularity of WebSocket also rely on support HTML5 standard browser updates, currently only a few browser Chrome, Safari, Firefox 4.0 can support, but the general trend of the drive, coupled with the popularity of smart mobile devices, WebSocket can have a greater role.

He solves the problem of Web real-time, which has the following advantages over traditional http:

    • A Web client establishes only one TCP connection
    • The WebSocket server can push (push) data to the Web client.
    • Have more lightweight head, reduce the amount of data transfer

This article focuses on the analysis.

Principle and application of WebSocket

Before continuing this article, let's look at the principles behind WebSocket:

WebSocket communication protocol is based on the native socket of the browser, so that only in the C/s mode of a large number of development mode can be moved to the web, basically through the browser support on the Web to achieve the server-side socket communication.

Instead of trying to simulate server push over HTTP, WebSocket defines the frame protocol directly above TCP, so websocket can support bidirectional communication.

The first step is to introduce the process of establishing a connection between the WebSocket client and the server:

First Use JS to create a WebSocket instance, using the WS protocol to establish a server connection, ws://www.cnodejs.org:8088

WS begins with a normal websocket connection, and WSS is a secure websocket connection, similar to HTTPS.

The client establishes a handshake with the server, sending the following information:
GET /echo HTTP/1.1
Upgrade: WebSocket
Connection: Upgrade
Host: http://www.cnodejs.org:8088
Origin: http://www.cnodejs.com

The server will send back the following:
HTTP/1.1 101 Web Socket Protocol Handshake
Upgrade: WebSocket
Connection: Upgrade
WebSocket-Origin: http://www.cnodejs.org
WebSocket-Location: ws://www.cnodejs.org:8088/echo

For specific WS-Protocols, refer to: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76

We do not need to consider the details of the protocol in the development process, because the WebSocket API has been packaged for us.

It is important to note that all communication data ends with "\xff" at the beginning of "\x00″" and is UTF-8 encoded.

This process is similar to the process of establishing an HTTP connection, but after the connection is established, any interaction between the client and the server needs to be followed. The client program is programmed with the following 4 events provided by the WebSocket API:

    • OnOpen trigger when connection is established
    • OnMessage triggers when a message is received
    • OnError triggered when an error occurs
    • OnClose triggered when the connection is closed

Let's take a full look at the WebSocket API, which is actually very simple, and here are all the APIs:

1234567891011121314151617181920212223
[Constructor (in Domstring URL, in optional domstring protocols)] [Constructor (in Domstring URL, in optional domstring[] protocols)]interface WebSocket {  readonly attribute domstring URL;  Ready state  Const unsigned short connecting = 0;  Const unsigned short OPEN = 1;  Const unsigned short CLOSING = 2;  Const unsigned short CLOSED = 3;  ReadOnly attribute unsigned short readyState;  ReadOnly attribute unsigned long bufferedamount;  Networking           attribute Function OnOpen;           Attribute Function onmessage;           Attribute Function onerror;           Attribute Function OnClose;  ReadOnly attribute domstring protocol;  void send (in domstring data);  void close ();}; WebSocket implements Eventtarget;

For a detailed websocket API, refer to this article: http://dev.w3.org/html5/websockets/

The combination of node. js and WebSocket

Finally, the topic, how to combine node. js with WebSocket, WebSocket API is event-based, he is for the client, and for the service side, how to deal with it? In fact, you can simply understand the development of socket server for implementing the WebSocket protocol.

node. JS is inherently an efficient service-side language that directly uses JavaScript to process requests from clients directly, so that if the server side needs a lot of business logic development, it can be developed directly using node. With the combination of node and websocket, we can develop a lot of real-time web applications, such as games, live, stock, monitor, IM and so on.

and node. js How to achieve websocket support, has a relatively mature open source system node-websocket-server:https://github.com/miksago/node-websocket-server, Let's explore one or two:

In fact, the principle is very simple is to use node to achieve the WebSocket draft-76 protocol, while he provides APIs, can facilitate other applications to simplify programming.

It inherits the HTTP of node. Server's events and methods, so that it simplifies programming on the service side and can handle HTTP requests.

To achieve communication between connections and broadcast messages, it implements a manager class that creates an ID for each connection, then maintains a linked list in memory, and provides automatic management of both on-line and offline.

It also provides an interface to the following events:

    • Listening when the server is ready to accept client requests
    • Request triggers when an HTTP request occurs
    • Stream
    • Close
    • Clienterror
    • Error

Let's take a look at an example of a server provided by Node-websocket-server:

123456789101112131415161718192021222324252627
var sys = require ("sys")  , WS = Require ('. /lib/ws/server '); var server = Ws.createserver ({debug:true});//Handle WebSocket Requestsserver.addlistener (" Connection ", function (conn) {  conn.send (" Connection: "+conn.id);  Conn.addlistener ("Message", function (message) {    Conn.broadcast ("<" +conn.id+ ">" +message);    if (message = = "Error") {      conn.emit ("Error", "Test");});}  ); Server.addlistener ("Error", function () {  console.log (Array.prototype.join.call (arguments, ","));}); Server.addlistener ("Disconnected", function (conn) {  Server.broadcast ("<" +conn.id+ "> Disconnected");}); Server.listen (8000);
This example is very simple, we can see the server-side development for WebSocket, we have no need to consider the implementation of the WebSocket protocol, he has almost the same as the client browser WebSocket API events, only to connect, disconnect, message, Errors and other events, so that the application development is very flexible. Example: Building a real-time monitoring system with websocket and node. js

After websocket through the browser and the server, we can try to build a real-world application, the real-time monitoring system for example.

The combination of direct and Linux monitoring tools, the monitoring results through WebSocket directly to the Web page, due to the establishment of a long socket connection, binding Iostat standard output events, to achieve real real-time. At the same time can support the discussion of monitoring results, added a simple chat, event-based communication, chat and monitoring simultaneous transmission is completely unaffected, so you can also add more events.

Let's take a look at this process:

The first is to capture the output of Iostat with node. JS:

123456
var sys = require ("sys")  , WS = Require ('. /lib/ws/server '); var sys = require (' sys '); var spawn = require (' child_process '). Spawn;var Mon = Spawn ("Iostat", ["-I", "5" ]);

Spawn can start a process based on the parameters, and can capture stdout, stderr, exit code, and when these events are triggered, we can bind our functions while capturing their output.
Here is the standard output of the Iostat:

disk0 cpu load average
KB/t tps MB/s us sy id 1m 5m 15m
14.64 4 0.06 7 5 88 0.76 0.95 0.90

We capture his output and send it to the client:

12345
  Mon.stdout.on (' Data ', function (data) {    data = format_string (data);    Sys.puts (data);    Conn.send ("#mon:" +data+ ");  });

The client is the browser, after the message is received, the simple string processing, and then you can directly in the Web page output.

123456789101112131415
W.onmessage = function (e) {    var msg = e.data;    if (Msg.match (/#mon:/)) {        var Monarr = Msg.split (":") [1].split ("");        var body = "";        For (var item in Monarr) {            body + = "<td id= ' Io_" +item+ "' >" +monarr[item]+ "</td>"        }        $ ("# Iobody "). HTML (body);        Log (monarr[0]);    }    else        log (e.data);}

A simple protocol for #mon is defined here, so that more types of output can be processed separately.

A real-time server performance monitoring system has been implemented with a total of more than 100 lines of code on the service side and the client.
Total Code: http://cnodejs.googlecode.com/svn/trunk/monsocket/examples/
(Note: This program is only tested under Mac OSX)

If you add RGraph (based on HTML5), you can create a more elegant real-time presentation: http://www.rgraph.net/docs/dynamic.html

Summarize

This article is intended for beginners of node. js, or for people who don't know websocket enough, to sum up the following points:

    • Use the WebSocket API to develop real-time Web applications
    • The WebSocket API and node. JS can be perfectly matched
    • Node-websocket-server encapsulates the WebSocket protocol, making the server WebSocket development, very simple
    • Node's ease-of-use makes it slightly programmable on the service side to create a perfect backend service
    • Node's event-driven mechanism ensures that the system is efficient and can use Eventemitter to define its own event triggering
    • You can use Spawn to capture command-line output by leveraging Linux's various system tools in Web applications

Resources

    • http://nodejs.org/
    • http://dev.w3.org/html5/websockets/
    • http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76
    • Https://github.com/miksago/node-websocket-server

This example is very simple, we can see the server-side development for WebSocket, we have no need to consider the implementation of the WebSocket protocol, he has almost the same as the client browser WebSocket API events, only to connect, disconnect, message, Errors and other events, so that the application development is very flexible.

WebSocket and node. js in perfect combination

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.