Node. JS builds a simple server for front-end test websocket linking methods and performance testing

Source: Internet
Author: User

WebSocket Introduction

When it comes to Web real-time push, you have to say Websocket. Before the advent of websocket, many Web sites in order to implement real-time push technology, the usual approach is polling (Polling) and Comet technology, Comet can be subdivided into two implementations, one is the long polling mechanism, a kind of called streaming technology, these two methods are actually the improvement of polling technology, These scenarios have obvious drawbacks, requiring the browser to issue HTTP request to the server, which consumes server bandwidth and resources heavily. In the face of this situation, HTML5 defines the WebSocket protocol to better conserve server resources and bandwidth and achieve real real-time Push.

WebSocket protocol is essentially a tcp-based protocol, which consists of communication protocols and programming apis, WebSocket can establish a two-way connection between the browser and the server, in an event-based manner, giving the browser real-time communication Capabilities. Since it is two-way communication, it means that the server side and the client can send and respond to the request at the same time, instead of requesting and responding like HTTP.

In order to establish a WebSocket connection, the client browser first initiates an HTTP request to the server, which differs from the usual HTTP request and contains additional header information, with the additional header information "upgrade:websocket" Indicates that this is an application protocol upgrade HTTP request, the server side to resolve these additional header information and then generate the response information returned to the client, the client and server side of the WebSocket connection is established, the two sides can pass through this connection channel free information, And the connection persists until either the client or the server side actively closes the Connection.

A typical websocket client request Header:

As mentioned earlier, WebSocket is a new communication protocol in HTML5, which means that some older browsers (mainly IE10 Below) do not have this feature, and the public data from Baidu statistics show that IE8 is still at the top of 33% market Share. fortunately, the market share of the Chrome browser is rising year by day, with more than 26% market share second, while Microsoft announced the end of the technical support for IE6 and prompted users to update to the new version of the browser, which has been a headache for many front-end engineers, the browser is expected to exit the historical stage, Plus almost all of the smartphone browsers support HTML5, so Websocket's real-world significance increases, But in any case, we still have to consider the compatibility of low-version browsers in our actual projects: using new technologies in a browser that supports websocket, In browsers that do not support websocket, Comet is enabled to receive Messages.

WebSocket Combat

This article will use the multiplayer live chat app as an example scenario, and we'll start by identifying the basic needs of this chat Application.

Demand analysis

1. Compatible with low-version browsers that do not support websocket.
2, allow the client to have the same user Name.
3, Enter the chat room can see the current online users and online number.
4, users on-line or exit, all online clients should be updated in Real-time.
5, the user sends the message, all clients collect in real Time.

In the actual development process, in order to use the WebSocket interface to build a web application, we first need to build a implementation of the WebSocket specification of the service side, the implementation of the server is not limited by the platform and development language, only need to comply with WebSocket specifications, At present, there are some more mature WebSocket server implementations, such as the Node.js+socket.io used in this paper. Why Choose this option? Let's start with a brief introduction to both of Them.

Node. JS

Node. js, written in the C + + language, is not a JavaScript application, but a JavaScript operating environment, according to the memory of Node. JS founder Ryan dahl, He initially wanted to use Ruby to write Node. js, but later found that the performance of the Ruby virtual machine did not meet his requirements, and later he tried to use the V8 engine, so he chose the C + + Language.

Node. JS supports systems including *nux, Windows, which means programmers can write system-level or server-side JavaScript code and give it to Node. JS to explain Execution. Node. Js's Web Development Framework Express helps programmers build Web sites quickly, and since 2009, Node. JS has grown at a remarkable pace, and its development prospects have been fully affirmed by the technical Community.

Socket.io

Socket.io is an Open-source WebSocket library that implements the WebSocket server through Node. JS and also provides a client JS Library. Socket.io supports event-based real-time bidirectional communication, which can work on any platform, browser or mobile Device.

Socket.io supports 4 protocols: WebSocket, htmlfile, xhr-polling, jsonp-polling, which automatically selects the appropriate communication method according to the browser, so that developers can focus on the implementation of the function rather than the compatibility of the platform, At the same time Socket.io has good stability and performance.

Encoding implementation

The illustration at the beginning of this article is the effect demo: you can click here to see the online demo, the whole development process is very simple, the following simple record the development steps:

Install Node. JS

Depending on your operating system, go to the Node. JS website to download and Install. If the installation is Successful. Enter node -v and npm -v should be able to see the corresponding version number on the command line.

Node-v  v0.10.26  npm-v  1.4.6  

Build WebSocket Service Side

This link we as far as possible to consider the real production environment, the WebSocket back-end service to build a line can be accessed by domain name services, If you are in the local development environment, you can switch to a local IP address, or use a virtual domain name to point to the local ip.

First go to your working directory, for example /workspace/wwwroot/plhwin/realtime.plhwin.com , create a new file named, with the package.json following content:

{  "name": "realtime-server",  "version": "0.0.1",  "description": "my First realtime server",  " Dependencies ": {}}

Next use npm the command to install express andsocket.io

NPM install--save expressnpm Install--save Socket.io

After successful installation, you should be able to see the working directory generated a node_modules folder named, which is express and socket.io , then you can start to write the server code, create a new file:index.js

var app = require (' Express ') (); var http = require (' http '). Server (app), var io = require (' socket.io ') (http), app.get ('/', function (req, res) {res.send (' 

Command line runs node index.js , if everything goes well, you should see the listening on *:3000 words returned, which indicates that the service has been successfully built. http://localhost:3000you should be able to see the normal Welcome page when you open it in the Browser.

If you want to let the service run online server, and can be accessed through the domain name, you can use Nginx proxy, add the following configuration in nginx.conf, and then the domain name (such as: realtime.plhwin.com) resolution to the server Ip.

Server  {    Listen       ;    server_name  realtime.plhwin.com;    location/{      proxy_pass http://127.0.0.1:3000;    }  }

After completing the above steps, http://realtime.plhwin.com:3000 the backend service is set up normally.

Service-side Code Implementation

The previous index.js code is just a simple webserver welcome content, Let's add the complete implementation code of the WebSocket service side, and the entire server can handle the Client's Request. The complete index.js code is as Follows:

var app = require (' Express ') (); var http = require (' http '). Server (app), var io = require (' socket.io ') (http), app.get ('/', function (req, res) {res.send (' 

Client code Implementation

Go to the client working directory /workspace/wwwroot/plhwin/demo.plhwin.com/chat and create a new one index.html :

<! DOCTYPE html>

The above HTML content itself is nothing to say, we mainly look at the inside of the 4 file request:
1, Realtime.plhwin.com:3000/socket.io/socket.io.js
2, Style.css
3, Json3.min.js
4, Client.js

The 1th JS is Socket.io provided by the client JS file, in front of the installation of the service side of the steps, when NPM installed Socket.io and set up webserver, the JS file will be able to access the Normal.

The 2nd style.css file nothing to say, is the style file Just.

The 3rd JS only in IE8 version of the Internet Explorer to load, the purpose is to allow these low version of IE browser can also handle json, this is an open source js, see: http://bestiejs.github.io/json3/

The 4th one client.js is the full Client's business logic implementation code, which reads as Follows:

(function () {var d = document,w = Window,p = Parseint,dd = d.documentelement,db = D.BODY,DC = D.compatmode = = ' Css1compat ', dx = dc? Dd:db,ec = Encodeuricomponent;w.chat = {msgobj:d.getelementbyid ("message"), screenheight:w.innerheight? W.innerheight:dx.clientheight,username:null,userid:null,socket:null,//keep the browser scroll bar at the lowest scrolltobottom:function () { W.scrollto (0, this.msgObj.clientHeight);},//exit, This example is just a simple refresh logout:function () {//this.socket.disconnect (); Location.reload ();},//submit Chat message content submit:function () {var content = d.getElementById ("content"). value;if (content! = ") { var obj = {userid:this.userid,username:this.username,content:content};this.socket.emit (' message ', obj); d.getElementById ("content"). value = ';} Return false;},genuid:function () {return new Date (). getTime () + "" "+math.floor (math.random () *899+100)},//update system messages, In this example, when the user joins and exits, call Updatesysmsg:function (o, action) {///current Online user list var onlineusers = o.onlineusers;//current online number var onlinecount = O.onlinecount;//new user information var user = O.user;//update Online number var userhtmL = "; var separator ="; for (key in Onlineusers) {if (onlineusers.hasownproperty (key)) {userhtml + = Separator+onlin    Eusers[key];separator = ', ';} }d.getelementbyid ("onlinecount"). InnerHTML = ' current total of ' +onlinecount+ ' people online, online list: ' +userhtml;//add system message var HTML = '; html + = ' & Lt;div class= "msg-system" > "html + user.username;html + = (action = = ' Login ')? ' joined the chat room ': ' exited the chat room '; html + = ' </div> '; var section = d.createelement (' section '); section.classname = ' System J-mjrlin Kwrap j-cutmsg '; section.innerhtml = html;this.msgobj.appendchild (section); this.scrolltobottom ();},// The first interface user submits the user name Usernamesubmit:function () {var username = d.getElementById ("username"). value;if (username! = "") { d.getElementById ("username"). value = ';d. getElementById ("loginbox"). style.display = ' None ';d. getElementById (" Chatbox "). style.display = ' Block '; this.init (username);} The return false;},init:function (username) {/* client generates the UID based on time and random numbers, which allows the chat room user name to be Duplicated. In the actual project, if the user is required to log in, then directly using the User's UID to do the identification can be */this.userid = This.genuid (); this.usernAme = Username;d.getelementbyid ("showusername"). InnerHTML = This.username;this.msgobj.style.minheight = ( This.screenheight-db.clientheight + this.msgObj.clientHeight) + "px"; This.scrolltobottom ();// Connect the websocket back-end server This.socket = Io.connect (' ws://realtime.plhwin.com:3000 ');//tell The server that a user is logged in This.socket.emit (' login ', {userid:this.userid, username:this.username}); /listen for new user login This.socket.on (' login ', function (o) {chat.updatesysmsg (o, ' login ');}); /listener user exits This.socket.on (' logout ', function (o) {chat.updatesysmsg (o, ' logout ');}); /listen message Send this.socket.on (' message ', function (obj) {var isme = (obj.userid = = chat.userid)? True:false;var contentdiv = ' &lt ;d iv> ' +obj.content+ ' </div> ' var usernamediv = ' <span> ' +obj.username+ ' </span> '; var section = D.createelement (' Section '), if (isme) {section.classname = ' user '; section.innerhtml = contentdiv + usernamediv;} else { Section.classname = ' service '; section.innerhtml = Usernamediv + contentdiv;} CHAT.msgObj.appendChild (section); Chat.scrolltobottom ();});}};/ /submit User name d.getElementById ("username") by "enter". onkeydown = function (e) {e = e | | event;if (e.keycode = = =) {CHAT.USERNAMESUBM It ();}};/ /"enter" to submit information d.getElementById ("content"). onkeydown = function (e) {e = e | | event;if (e.keycode = =) {chat.submit ();}};}) ();

At this point all the coding development work is complete, open http://demo.plhwin.com/chat/in the browser can see the Effect.

All of the above-mentioned client and server code can be obtained from github, address: https://github.com/plhwin/nodejs-socketio-chat

git clone https://github.com/plhwin/nodejs-socketio-chat.git 

Download local after two folders client and, the server client folder is the client source code, can be placed in the Nginx/apache webserver, can also be placed in Node. JS Webserver. The code in the latter server folder is the WebSocket server code, which is placed in the Node. JS environment, express and after the installation and use of NPM socket.io , node index.js start the backend service.

This example is just a simple demo, leaving 2 thoughts about the project Extension:

1, The assumption is an online customer service system, There are many companies use your services, each Company's own users can enter the Company's chat room through a dedicated URL address, chat is one-to-one, each company can create a new number of customer service personnel, each customer service personnel can simultaneously and the Client's multiple users chat.

2, also assumed to be an online Webim system, to achieve similar, QQ function, the client can see friends online status, online list, add friends, delete friends, new groups, etc., the message in addition to support the basic text, but also support emoticons, pictures and Files.

From: http://www.plhwin.com/2014/05/28/nodejs-socketio/

Node. JS builds a simple server for front-end test websocket linking methods and performance testing

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.