现在很流行的websocket的实现socket.io同样包括客户端和服务器端两部分。它不仅简化了接口,使得操作更容易,而且对于那些不支持WebSocket的浏览器,会自动降为Ajax连接,最大限度地保证了兼容性。它的目标是统一通信机制,使得所有浏览器和移动设备都可以进行实时通信。
首先我们需要保证设备已经安装了node.js,我们后续的开发工作都在node环境中执行,如果没安装请点击这里Node.JS;
然后我们就可以开始编写程序了:
- 新建package.json,里面包含了我们开发中所用到的依赖
{
"name": "socket-chat-example",
"version": "0.0.1",
"description": "my first socket.io app",
"dependencies": {
}
}
- 结合express框架进行编写,我们用
npm install --save
,以便可以方便加到我们的dependencies中;
npm install --save express
- 现在我们可以编写
index.js
文件
var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res){
res.send('<h1>Hello world</h1>');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
这转化为以下内容:
- Express初始化
app
为可以提供给HTTP服务器的函数处理程序(如第2行所示)。 - 我们定义一个路由处理程序
/
,当我们访问我们的网站时,它会被调用 - 我们使http服务器侦听端口3000。
If you runnode index.js
you should see the following:
And if you point your browser to http://localhost:3000
:
提供HTML
到目前为止,index.js
我们正在调用res.send
并传递一个HTML字符串。如果我们将整个应用程序的HTML放在那里,我们的代码看起来会很混乱。相反,我们将创建一个index.html
文件并提供服务。
让我们重构我们的路由处理程序来sendFile
代替:
app.get('/',function(req,res) {
res.sendFile(__ dirname + '/ index.html');
});
并填充index.html
以下内容:
<!doctype html>
<html>
<head>