The websocket of new characteristics of HTML5

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

First, WebSocket simple introduction:

When it comes to web real-time push, you have to say websocket. Before the advent of websocket, very many sites were implemented in order to implement real-time push technology. Commonly used scenarios

is polling (Polling) and comet technology, comet can be subdivided into two ways, one is the long polling mechanism. A technique called flow. Both of these approaches are actually

The improvement of polling technology. These scenarios present a very obvious drawback, requiring the browser to issue an HTTP request to the server. Consume server bandwidth and resources heavily. Face

Such a situation. HTML5 defines the WebSocket protocol to better conserve server resources and bandwidth and achieve real real-time push.

The WebSocket protocol is essentially a TCP-based protocol. It consists of communication protocols and programming APIs 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. means that the server side and client can send and respond at the same time,

Please. And no longer like HTTP requests and responses.

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. Including

Some additional header information. 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 reply message to the client. The WebSocket connection between the client and server side is set up. The two sides will be able to pass this connection channel freely

The delivery information. And this connection persists until either the client or one of the server side actively closes the connection.

A typical websocketclient request header:


Note:WebSocket is a new communication protocol in HTML5 , which means that part of the old version of the browser (mainly IE10 the following version number) does not have this feature.

IE8 is still occupying the top spot with 33% of the market share, but the market share of chrome is rising every year, with more than 26%

The market share was second, and at the same time Microsoft announced that it would stop technical support for IE6 and prompt users to update to the new version number browser. This used to be the head of countless front-end project architects.

The pain of the browser is expected to exit the historical stage, coupled with almost all of the smartphone browser support HTML5, so that the actual combat significance of websocket greatly increased. But no matter

How, in our actual project, we still have to consider the compatibility of the low version browser: Using new technology in a browser that supports WebSocket, without supporting Websocke

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

Browser Support list:



Second, WebSocket Combat:

This article uses the multiplayer live chat app as an instance scenario. Let's start by identifying the basic needs of this chat application.

Requirements Analysis:

1, compatible with the low version number browser does not support WebSocket.

2, agree that the client has the same username.

3, enter the chat room can see the current online users and online number.

4, users on-line or exit, all the online client should be updated in real time.

5, the user sends the message, all the client receives in real time.


In the actual development process. To build a web app using the WebSocket interface. We first need to build a service side that implements the WebSocket specification.

The implementation of the server is not limited by the platform and development language, but only by complying with the WebSocket specification. Some of the more mature WebSocket have now emerged.

Service-side implementations, such as the Node.js+socket.io used in this article.

Why use this method? The following is a first introduction.


node. JS:

node. JS is written in the C + + language. It is not a JavaScript application, but a JavaScript execution environment. According to the founder of node. JS Ryan Dahl recalled.

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 he later tried to use the V8 engine. So choose

The C + + language.

node. JS supports systems that contain *nux, Windows, which means that program apes can write JavaScript code at the system level or server side. Give it to node. js

Explain the run. node. JS's Web Development Framework Express. Able to help program ape to build Web sites at high speed, since the birth of 2009, 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 CLIENTJS libraries at the same time.

Socket.io Support to

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

Socket.io supports 4 kinds of protocols: WebSocket, Htmlfile, xhr-polling, jsonp-polling. It will voluntarily choose the appropriate means of communication according to the browser,

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


Finally effect:


Development steps

(1), install node. js

From the operating system, go to the node. JS website to download and install. Assume that the installation was successful. At the command line, enter node-v and npm-v should be able to see the corresponding version.

Watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqv/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70/gravity /center ">

(2), build WebSocket service end

This link we consider the real production environment as much as possible. Build WebSocket backend services into a service that can access domain names online, assuming you are in the local development environment,

Be able to switch to a local IP address, or use a virtual domain name to point to the local IP.

Go to your working folder first. For example/workspace/wwwroot/plhwin/realtime.plhwin.com, create a new file named Package.json with the following contents:

{  "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 a successful installation. You should be able to see a folder named Node_modules under the working folder, each of which is express and Socket.io, and then you can start writing

The code of the service side. 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 (' 
The command line executes node index.js. Assuming everything goes well, you should see the listening on *:3000 returned, which indicates that the service has been successfully built.

Now open in Browser

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

Suppose you want the service to execute online server. and can through the domain name interview, can use Nginx agent. Add a configuration such as the following in nginx.conf, and then add the domain name

(For example: realtime.plhwin.com) resolution to ServerIP can be.

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.

Watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqv/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70/gravity /center ">

(3), service-side code implementation

The previously mentioned Index.js executes on the server side, the previous code is just a simple webserver welcome content, let us add the WebSocket server complete implementation code to go in,

The client's request can be processed by the entire server. The complete index.js code such as the following:

var app = require (' Express ') (); var http = require (' http '). Server (APP), var io = require (' Socket.io ') (HTTP), App.get ('/', function (req, res) {res.send (' 
IV. Implementation of client code

Enter the client working folder/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 Clientjs 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 has nothing to say. is a style file.

The 3rd JS is only loaded in the IE8 version of IE browser, the purpose is to let these low version of the IE browser can also handle JSON. This is an open source JS, see: http://bestiejs.github.io/json3/

The 4th Client.js is the complete client of the business logic implementation code, its contents such as the following:

(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 part of 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, This example calls Updatesysmsg:function (O, action) {//Current online user list var onlineusers = o.onlineusers;//Current online number var Onlinecount = When the user increments or exits o.onlinecount;//new user Information var = o.user;//Update online number var userhtml = '; var separator = '; for (key in onlineusers) {if (Onlineusers.hasownproperty (key)) {userhtml + = Separator+onlineusers[key];separator = ', ';} }d.getelementbyid ("Onlinecount"). InnerHTML = ' currently co-owned ' +onlinecount+ ' people online, online list: ' +userhtml;//add system message var HTML = '; HTML + + ' <div class= ' Msg-system > '; HTML + user.username;html + = (Action = = ' login ')? ' Added 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 repeated. In the actual project, assuming that the user is required to log in, then directly using the user's UID to make the identity 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 ();//connection WebSocket back end serverthis.socket = Io.connect (' ws://realtime.plhwin.com:3000 '),//Tell the server user to log in this.socket.emit (' login ', {userid:this.userid, username: This.username});//monitor 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.usernamesUbmit ();}};/ /"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. You can see the effect by opening http://demo.plhwin.com/chat/in the browser.

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


Download local after two directory client and server,client directory is the source code, can be placed in the Nginx/apache webserver,

can also be placed in the webserver of node. js. The code in the following server directory is the WebSocket service-side code. Placed in the node. JS Environment

, after installing Express and Socket.io with NPM, node index.js starts back-end service.

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

1, if it is an online customer service system, there are a lot of companies using your services, each company's own users can pass a dedicated URL address

Into the company's chat room, chat is one-to-two, each company can create a new number of customer service personnel, each customer service staff can be at the same time and the client's multiple users chat.

2, if it is an online Webim system, achieve similar. QQ function, the client can see friends online status, online list. Join a friend,

Delete Friends. New groups, and so on. Messages are sent in addition to supporting the main text. You can 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.