The websocket of new characteristics of HTML5

Source: Internet
Author: User
Tags button type emit live chat install node hasownproperty

First, WebSocket Introduction:

When it comes to web real-time push, you have to say websocket. Before the advent of WebSocket, a number of sites were typically used to implement real-time push technology.

is polling (Polling) and comet technology, comet can be subdivided into two implementations, one is the long polling mechanism, which is called the flow technology, these two methods are actually

The improvement of polling technology, which brings obvious shortcomings, requires the browser to issue HTTP request to the server, which consumes the server bandwidth and resources greatly. Face

In this situation, HTML5 defines the WebSocket protocol, which can better conserve server resources and bandwidth and achieve real-time push delivery.

The WebSocket protocol is essentially a TCP-based protocol that consists of a communication protocol and programming API that WebSocket can establish between the browser and the server

Bidirectional connectivity that gives the browser real-time communication capabilities in an event-based manner. Since it is two-way communication, it means that the server side and the client can send and respond at the same time,

Requests and responses that are not 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

Some additional header information, where the additional header information "Upgrade:websocket" indicates that this is an HTTP request to request a protocol upgrade, and the server side resolves these additional

The header information is then generated to return the response to the client, and the client and server-side websocket connections are established, and the connection channel is free for both parties

, and the connection persists until either the client or the server side actively closes the connection.

A typical WebSocket client request header:


Note:WebSocket is a new communication protocol in HTML5 , which means that some older browsers (mostly IE10) do not have this feature,

According to the public data of Baidu statistics, IE8 still occupy the top spot with 33% market share, fortunately, the market share of Chrome browser is rising year in and now more than 26%

The market share was second, and Microsoft soon announced that it would stop technical support for IE6 and prompt users to update to the new version of the browser, which once made the head of countless front-end engineers

The pain of the browser is expected to exit the historical stage, coupled with almost all of the smart phone browser support HTML5, so that the actual combat significance of websocket, but no matter

How, in our actual project, we still have to consider the compatibility of the low-version browsers: Using new technologies in browsers that support WebSocket, without supporting Websocke

T's browser enables comet to receive a send message.

Browser Support list:



Second, 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.

Requirements 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,

Service-side implementation is not limited by the platform and development language, only need to comply with the WebSocket specification, there have been some relatively mature WebSocket

Service-side implementations, such as the Node.js+socket.io used in this article. Why choose this option? The following is a first introduction.


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 discovered 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 the execution. node. JS's Web Development Framework Express, can help programmers quickly build Web sites, since 2009 was born, node. JS's growth rate

It is obvious that 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 Support to

Event-based real-time bidirectional communication, which can work on any platform, browser or mobile device.

Socket.io supports 4 kinds of protocols: WebSocket, Htmlfile, xhr-polling, jsonp-polling, which automatically selects the appropriate communication method according to the browser,

This allows developers to focus on the implementation of the feature rather than the compatibility of the platform, while Socket.io has good stability and performance.


Final effect:


Development steps

(1), install node. js

According to the operating system, go to the node. JS official website. If the installation is successful. Enter Node-v and npm-v at the command line to see the corresponding version number.


(2), build WebSocket service end

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.

Go to your working directory, such as/workspace/wwwroot/plhwin/realtime.plhwin.com, and create a new file named Package.json, which reads as follows:

{  "name": "Realtime-server",  "version": "0.0.1",  "description": "My first realtime Server",  " Dependencies ": {}}
Next use the NPM command to install Express and Socket.io
NPM Install--save expressnpm install--save Socket.io
After successful installation, you should be able to see the working directory generated a folder named Node_modules, which is express and Socket.io, then you can start to write

Service-side 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 run node Index.js, if all goes well, you should see the listening on *:3000 returned, which indicates the service has been successfully built. Now open in Browser

http://localhost:3000 should be able to see the normal welcome page.

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

(For example: realtime.plhwin.com) resolves 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, the http://realtime.plhwin.com:3000 backend service is set up normally.

(3), service-side code implementation

the previously mentioned index.js run on the server side, the previous code is just a simple webserver welcome content, let us put the WebSocket server complete implementation code to join in,

The client's request can be processed by the entire server. 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 (' 
Iv. Client Code implementation

go to client working directory/workspace/wwwroot/plhwin/demo.plhwin.com/chat, create a new 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 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


Download local after two folders client and Server,client folder is the source code, can be placed in the Nginx/apache webserver,

It can also be placed in the webserver of node. js. The code in the following server folder is the WebSocket service-side code, which is placed in the node. JS Environment

, after installing Express and Socket.io using NPM, node index.js starts the backend service.

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

1, suppose is an online customer service system, there are many companies use your services, each company's own users can pass a dedicated URL address

Into the company's chat room, chat is one-to-many, each company can create a new number of customer service personnel, each customer service staff 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, create new groups, etc., send messages in addition to supporting basic text, but also support emoticons, pictures and files.

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

The websocket of new characteristics of HTML5

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.