开始吧,我们做个聊天应用!在这个教程里,我们将制作一个简单的网页聊天应用。它机会不要求你有任何关于Node.js 或 Socket.io 的基础,所以这份教程适合任何水平的开发者。先看看Demo 。 介绍曾经写一个网页聊天应用可能会用到网页工具套件LAMP、PHP,那时候非常困难。因为客户端要不断地像服务器发送请求,查看是否有信息变化,体验起来非常慢。 Socket 通信是传统解决实时通讯的一种方案,它提供了服务器和客户端之间的双向通信。
这就意味着,服务器可以把消息推送给客户端,无论何时你发送了一个消息,客户端都能接受到你的消息,并将它推送给其他连接的用户。 网站框架我们的第一个目标是建立起一个简单的 HTML 页面(提供一个提交输入信息的Form表单,和一个对话的列表)。我还还将通过 Node.js 的web框架 express 。首先,我们需要保证电脑已经安装了 Node.js (如何安装Node) 。 第一步,我们先创建一个 package.json 文件,它用来描述这个项目。我推荐你把它放在一个新建的空文件夹内。(我把我新建的文件夹名叫做 chat-example .) {
"name": "socket-chat-example",
"version": "0.0.1",
"description": "my first socket.io app",
"dependencies": {}
}
现在,为了简单的 package.json 中的 dependencies (依赖),我们将使用npm install --save 命令。 npm install --save express@4.10.2
现在,我们已经装好了 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');
});
这三段代码可以解释为: 如果你在浏览器中输入
http:

提供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>
<title>Socket.IO chat</title>
<style>
body,form,#message,li {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font: 13px Helvetica, Arial;
}
form {
background: #000;
padding: 3px;
position: fixed;
bottom: 0;
width: 100%;
}
form input {
border: 0;
padding: 10px;
width: 90%;
margin-right: .5%;
}
form button {
width: 9%;
background: rgb(130, 224, 255);
border: none;
padding: 10px;
}
#messages {
list-style-type: none;
margin: 0;
padding: 0;
}
#messages li {
padding: 5px 10px;
}
#messages li:nth-child(odd) {
background: #eee;
}
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" />
<button>Send</button>
</form>
</body>
</html>
如果你重启了这个进程(按 Ctrl/Cmd + C再 输入 node index.js ),刷新页面就可以看到:  使用Socket.ioSocket.io由两部分组成: 一个Node.js HTTP服务器的应用 socket.io (此处原文为:A server that integrates with (or mounts on) the Node.JS HTTP Server: socket.io) 一个客户端的js库 socket.io-client 我们只需安装一个模块就可以来使用: npm install --save socket.io 这样会自动保存 dependency 到 package.json 。现在,我们开始编辑index.js 吧! var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendfile('index.html');
}); io.on('connection', function(socket){ console.log('a user connected');
}); http.listen(3000, function(){ console.log('listening on *:3000');
}); 注意到,我通过传递了http对象(HTTP服务器)新建了一个 socket.io 实例,接着,我对传递进来的套接字(socket),监听 connection 事件,并将事件答应到console。
现在在 index.html 中,我在 </body> 添加了如下语句: <script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
这会让网页加载 socket.io-client ,它会暴露一个 io 全局对象,并连接socket。 注意:当我调用 io() 时,我没有特别声明任何 url 。因为它默认连接这个页面的host服务器。 如果你重现启动服务器,你将会看到console输出“a user connected”。多打开几个页面,你将会看到:  每个socket同样会触发 disconnect 事件: io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
这样你刷新网页的多次,你就会看到:  触发事件Socket.IO 背后最主要的作用时可以让服务器和客户端发送和接受事件触发,任何能被编辑成 JSON或二进制 的对象都可以传递。
我们先来实现这种情况:用户输入信息,服务器端接收到 chat message 事件,这是 index.html 中的 script 应该这样写: <script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
</script>
在 index.js ,我们输出 chat message 事件: io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
});
广播下一个目标就是由服务器触发每一个客户端的事件 为了给每个客户端发送时间, Socket.io提供 了 io.emit : io.emit('some event', { for: 'everyone' });
如果你想给每个人发送消息,出了某个特定的socket连接,我们可以用 boardcast标示符: io.on('connection', function(socket){
socket.broadcast.emit('hi');
});
在我们这个项目中,为了简便,我们给每个连接的用户都发送消息 io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
在客户端这一侧,当我们捕获到了 chat message 事件,我们将它体现在页面中,所有的JavaScript如下: <script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
这时我们就完成了我们的聊天应用,仅仅只有20行代码!!! |