好的程序员了解多种编程语言(programming language)、框架和平台,这使他们可以设计出最合理的解决方案 - 不仅能够满足当前的业务需求,同时也是一个可扩展的(scalable), 易于维护的(maintainable),并且是可复用的(reusable)的有活力的系统。在过去的三年中,出现了一种新的编程语言Node.js,目前他已成为Github上下载量排名第二的开源语言,倍受服务器端应用程序开发者的喜欢。
Node.js是一个为可升级网络程序(scalable network application)提供了一个平台。它建立在Google V8 Javascript Engine之上。提供了一套单线程、基于事件的交互模式。我们可以把Node.js看作一个轻量级的服务器,它同时支持大量并发连接,却并不需要很大的内存,因为服务器并不借助内存维护每个连接的状态,而且使用单线程处理工作队列(Work Queue)中的事件。如下图:
从部署安装的角度来看,Node.js引擎只包含一个小于5M的的可执行程序,可以安装在Windows, Linux和MacOS上。它使用了高度模块化的框架,除了一些自带的模块处理简单的HTTP,TCP请求。Node.js有非常强大的开源社区,可以从中下载大量开发者发布的其他模块。对于扩展模块的下载,Node.js提供了Node Package Manager (npm)。借助这一工具,开发者可以方便的得到各种各样的扩展模块包。
使用Node.js引擎,只需下面的5行程序,就可以实现一个HTTP服务器,并在网页上打印Hello World。
var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n');}).listen(8080); console.log('Server running on port 8080');
我们用下面的例子来进一步理解Node.js的工作机制。
在开始下面的实验之前,你需要到 http://nodejs.org/download/ 下载并安装。
这个实验描述了Node.js如何实现Web浏览器和服务器之间的实时交流,例如在线聊天、视频游戏等。要实现这类场景,传统的方法是在服务器和客户端之间建立长连接。随着HTML5标准的发布,WebSockets提供了这样一种机制:利用一个socket连接,服务器与客户端之间可以进行全双工的交流。这里需要注意,WebSockets需要最新的浏览器的支持,例如IE10。在Node.js中使用WebSockets,需要第三方模块的支持 - Socket.IO。Socket.IO基于事件驱动,实现服务器和客户端的实时交流,请参考下图:
图中,Web浏览器1向服务器发送一个事件(Event),服务器接收到这个事件,并将该事件用广播的方式传送到每一个与之连接的Web浏览器(Web Browser2, Web Browser 3)中。
1. 在任意磁盘驱动器上创建一个空目录,例如:D:\nodejs\sockets
2. 用下面的代码创建server.js文件。
// Include needed packages (socket.io and express) var express = require('express'); var app = express() , http = require('http') , server = http.createServer(app) , io = require('socket.io').listen(server); // REPLACE BELOW var port = var port = process.env.PORT || 8080; // Allow connections on port 8080, or the environment port number var port = process.env.PORT || 8080; // At the time of this writing, WebSockets is not supported // in Windows Azure Web Sites, which will force socket.io // to fallback to a different communication protocol. // Prevent potential problems by specifying one, in this case, xhr-polling. io.set('transports', ['xhr-polling']); // Listen for incoming requests server.listen(port); // Redirect request to index.html app.get('/', function (req, res) { res.sendfile(__dirname + '/index.html'); }); // When connected and sendmessage is called by client, // broadcast data sent by one client to all connected clients io.sockets.on('connection', function (socket) { // When the client emits 'sendmessage,' the following method is triggered socket.on('sendmessage', function (data) { // Message is broadcast to all clients socket.broadcast.emit('displaymessage', data); }); });
3. 在同样的目录下,用下面的代码创建index.html文件。
<html> <head> <script src="/socket.io/socket.io.js"></script> <script> // Initialize the socket connection var socket = io.connect(); // Ask client (browser input box) to enter text function sendMessage(){ socket.emit('sendmessage', prompt("Message to broadcast?")); } // Displaymessage event received at all clients // display in alert dialog box socket.on('displaymessage', function(data){ alert(data); }); </script> </head> <body> <!—Client sends user input to node.js server through the sendMessage JavaScript function--> <input type="button" value="Broadcast new message" onClick="sendMessage();"> </body> </html>
4. 打开一个命令行工具。注:对于Win8操作系统,你可以直接打开Node.js Command Prompt,这样下面所需的系统变量PATH就不需要单独配置了。否则需要手动将npm.cmd和node.exe加入系统PATH变量。
5. 确保你的电脑有网络连接。在命令行中打入:npm install socket.io。这里命令将下载并安装Socket.IO这个模块。
6. 在命令行中打入:npm install express。借助Express模块可以方便的建立HTTP连接,并与Socket.IO有很好的集成。
7. 在命令行中打入:node server.js
8. 打开支持WebSockets的浏览器(例如IE10),键入连接地址:http://localhost:8080
9. 在打开一个网页,键入同样的地址:http://localhost:8080
10. 在一个浏览器中输入要广播的内容,其他所有连接到服务器的浏览器都会收到消息。
发送消息的浏览器:
其他连接到服务器的浏览器:
Node.js本地测试成功!