WebSocket A Web communications revolution quietly coming--node.js Touch Stone series of five

Source: Internet
Author: User

Transferred from: http://www.cnblogs.com/hsxixi/archive/2011/12/24/2300641.html

From this time on, let's set up a simple chat room. Because the HTTP protocol is stateless, building a chat room like this has never felt gegedada is not so logical. If you do not use the flash, applets and other browser plug-ins, we need to periodically poll the server to get everyone's chat information. This creates a certain amount of latency and a lot of network traffic.

But as HTML5 emerges, the situation is expected to be radically improved. Among the many features of HTML5, there is a big brother who is always quietly behind the scenes, he is WebSocket. WebSocket is really too powerful, Firefox browser in support for a period of time, I feel really can not guarantee that the eldest brother will not do something special, put him limbo. But as Mao Sui said, nails in the pocket, sooner or later, will come out of the head. Now the latest version of Chrome, Firefox support WebSocket, as well as IE 10 is also said to support.

What is WebSocket?

When it comes to explaining WebSocket, we need to look at the HTTP comparison to see how valuable he is.

http

websocket

bidirectional, but half duplex

bidirectional full duplex

stateless

persistent connection

High latency

real-time, event-driven

High bandwidth consumption

Low bandwidth consumption

for document design

/td>

document, binary both, client not limited to browser

Well, compared to the end, if you are still a little confused, ah, then I work hard, make an analogy good. We compare the server to be a beautiful princess, we are the poor, one of the Seekers. HTTP era: We wrote a letter (request), to book, quick, send a message to, don't lazy on the road. Book to the Palace of the Princess, was stopped at the door, surrender flagging (Request headers), oh, go in. Fortunately, the princess is also very enthusiastic about us, soon wrote the letter (response), put in the envelope, labeled (response Headers), to book. Book back to us with a fart and a jerk. As we and the princess's feelings continue to warm up, we began to keep a group of pigeons called Ajax, so that we can quickly write our little poem small words to the princess. If the princess think of us, we can also when there is a carrier pigeon to come, her handkerchief or something tied to the pigeon leg to send us back. HTML5 era, we and the relationship between the princess began to be inseparable, just rely on letters and notes can not be satisfied, fortunately, we have WebSocket, as long as we let book send a letter, WebSocket will come between us and the princess to set up a telephone hotline, So the princess can hear you immediately, you speak the princess can immediately hear, of course, because this line is two-way full duplex, you can also sing together a small love song.

Well, next to the personal understanding, do not know right, right when reference: WebSocket is to implement the handshake through the HTTP protocol socket.

Here is an excerpt from the Kaazing websocket–the Web communication Revolution:

Second, what can WebSocket do?

Theoretically, what the socket can do is what he can do.

The answer to this question mark is infinite, let's take a look at this online version of the Quake game, maybe he can light up our brains.

Homework: With your Ben, me, ego, ego, I have a brainstorming meeting to discuss WebSocket's profound impact on WEB application development.

Iii. WebSocket protocol and Socket.io module

The WebSocket specification consists of the client and server-side specifications respectively. The client is developed by the consortium and the server-side specification is developed by the IETF. node. JS's third-party module Socket.io provides the ability to use the WebSocket protocol on node. js.

Enough has been said, the following hands.

Build a project folder, here I use chatroom good, you help yourself. Open a command-line window and go to the chatroom directory and type the following command:

d:\chatroom> NPM Install Socket.io–d

See figure: (The-D parameter allows us to observe the details of the installation, but there is information that –d is installed to all dependent packages, no matter what, plus the total is not good, right? )

If the last "NPM info OK" appears, congratulations, the Socket.io module is installed successfully. View the chatroom directory and get the following structure:

Four, or first hit the foundation

When the preparation is done, let's write the most minimalist shelf and test him.

Please look at the code:

1234567891011121314151617181920212223 /* 平安夜快乐之聊天室框架 *///照例先引入模块,这次我们需要 http 和 socket.io 两个varhttp = require(‘http‘),    socketio = require(‘socket.io‘);    //注意,和前面的区别是我们需要拿到 http 创建的服务器实例varapp = http.createServer(function(request,response){    //TODO 后面我们会在这把聊天室页面发回去,不过现在我们简单地提示就好了。    response.end(‘Server ok.‘);}) ;//http 服务开始侦听app.listen(888);console.log("Http Server start at 888");// socket.io 开始侦听var io = socketio.listen(app);// WebSocket 协议握手成功io.sockets.on(‘connection‘,function(socket) {    console.log("Websocket connect ok ...");});

remain as app.js files. Run.

d:\chatroom> node App.js

If you see such as, then congratulations, WebSocket is ready to serve our chat room.

Look at the tip the first line is our output of the description of the HTTP service startup information, the second line is node. js, or exactly the Socket.io to give us the message, really thoughtful ah. Listen, did they lie about the military? Try it and know it.

Please open the browser, and so on, what browser is OK? Didn't you say it was just Chrome and Firefox? Well, I almost forgot, Socket.io not only helped us achieve the WebSocket protocol, but also helped us improve browser compatibility, and now supports ie5+, Safari, Chrome 4+, Firefox, Opera 10.61+, Also supports some mobile phones and tablets on the browser.

    • In the Address bar, type:

Http://localhost:888/socket.io/socket.io.js

Observing the console and browser, you will find the console prompt you: debug–served static content/socket.io.js, and the browser we also get a section, no, a large segment of the JS code, which shows that our task is complete. Http Service Normal, WebSocket service normal, Rocket is about to launch!

WebSocket A Web communications revolution quietly coming--node.js Touch Stone series of five

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.