Node.js(http://nodejs.org/)是服务器平台程序,它包含若干个基于Goole的JavaScriptV8引擎的库,2009年,Ryan Dahl创建了Node.js,它可用来创建快速,可扩展的网络应用,Node.js使用一种事件驱动、无阻碍、轻量级、高效的I/O模型。
一. 安装和配置node.js
下载地址:http://www.nodejs.org/download/,下载完成后运行node-v0.12.7-x86.msi,默认的安装路径是C:\\Program Files(x86)\nodejs\下。
Win7下的安装:
打开命令行,键入C:,跳到C盘下,键入cd Program Files(x86),cd nodejs,跳到nodejs下,安装一系列模块,不知道为什么安装nodejs的时候不一起装。
安装相关模块:
键入命令:
npm express 回车等待安装express
npm mysql 回车等待安装mysql
npm jade 回车等待安装jade.
至此安装和配置已经完成,命令行输入 node -v 可以查看nodejs的版本,下面是一个简单的html页面和nodejs服务器。
二. 使用Nodejs开发服务器
简单的html页面(websocketclient.html):
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>WebSocket Client</title>
<script type="text/javascript" charset="UTF-8">
var websocket;
var serverUrl = 'ws://localhost:8080/';
function displayMessage(message) {
document.getElementById('displaydiv').innerHTML += message + '<br>';
}
//初始化websocket对象并设置事件响应方法
function initWebSocket() {
//检查浏览器是否有一份websocket的实现(老版本的火狐浏览器使用MozWebSocket)
var WebSocketObject = window.WebSocket || window.MozWebSocket;
if(WebSocketObject) {
//创建websocket对象
websocket = new WebSocketObject(serverUrl);
//建立事件响应方法
websocket.onopen = function() {
displayMessage("WebSocket 链接已经打开");
document.getElementById('sendmessage').disabled = false;
};
websocket.onclose = function() {
displayMessage("WebSocket 连接已经关闭");
document.getElementById('sendmessage').disabled = true;
};
websocket.onerror = function() {
displayMessage("WebSocket 连接错误");
// document.getElementById('sendmessage').disabled = false;
};
websocket.onmessage = function(message) {
displayMessage('收到消息:<i>' + message.data + '</i>');
};
}
else {
displayMessage('你的浏览器不支持WebSocket!');
}
}
//使用webSocket向服务器发送数据
function sendMessage() {
//readyState可以为CONNECTING, OPEN, CLOSING, CLOSED
if(websocket.readyState == websocket.OPEN) {
var message = document.getElementById('message').value;
displayMessage('发送信息:<i>' + message + '</i>');
websocket.send(message);
}
else {
displayMessage('webSocket没有打开,无法发送消息!');
}
}
</script>
</head>
<body onload="initWebSocket();">
<label for="message">Message</label>
<input type="text" value="Simple Message" size="40" id="message" />
<input type="button" value="发送" id="sendmessage" onclick="sendMessage()" disabled="true" />
<div id="displaydiv" style="border:1px solid:black;width: 600px;height: 400px;font-size: 14px">
</div>
</body>
</html>
简单的nodejs服务器(websocketserver.js):
var http = require('http');
var server = http.createServer(function(request, response) {
console.log('Received HTTP request for url: ', request.url);
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('This is a simple node.js HTTP server. Hello World');
});
//侦听8080端口
server.listen(8080, function() {
console.log('Server has started listening on port 8080');
});
//向HTTP服务器添加webSocket服务器
var WebSocketServer = require('websocket').server;
console.log(require('websocket'));
var wsServer = new WebSocketServer({httpServer: server});
//判断指定的连接是否被允许
function connectionIsAllowed(request) {
//检查诸如request.origin, request.remoteAddress等条件
return true;
}
//处理webSocket连接请求
wsServer.on('request', function(request) {
//某些条件下拒绝请求
if(!connectionIsAllowed(request)) {
request.reject();
console.log('WebSocket Connection from ' + request.remoteAddress + ' rejected.');
return;
}
//接收连接
var websocket = request.accept();
console.log('WebSocket Connection from ' + request.remoteAddress + ' accepted.');
websocket.send('Hi there. You are now connected to the webSocket server.');
websocket.on('message', function (message) {
if(message.type === 'utf8') {
console.log('Reveived Message: ' + message.utf8Data);
websocket.send('Server received your message: ' + message.utf8Data);
}
});
websocket.on('close', function(reasonCode, description) {
console.log('WebSocket Connection from '+ request.remoteAddress + ' closed.');
});
});
启动nodejs服务器:
命令行键入F: ,跳到F盘下,cd LastColony,cd websocketdemo 跳转到Js文件目录下,输入node websocketserver.js运行js文件,就可以看到命令行输出:Server has started listening on port 8080。表示服务器启动正常了。
在运行websocketserver.js的时候可能会遇到一个问题,提示can not find modult 'websocket',很简单,这是因为websocket模块没有安装而已,命令行键入 npm websocket 后按回车,等待模块安装后再运行程序。