socket.io是个基于node.js的快平台实时通讯框架。只用不到10行代码,就可以搭建一个简单的多人实时聊天室。
先来看看运行后的效果:
socket.io多人聊天室
只要简单几步,就可以实现。在这里我们使用本机作为服务端。
安装node.js
由于socket.io使用node.js为服务端,所以必须安装node.js
Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境。Node.js 使用了一个事件驱动、非阻塞式 I/O 的模型,使其轻量又高效。Node.js 的包管理器 npm,是全球最大的开源库生态系统。
编写package.json
新建一个项目文件夹,编写package.json文件来描述项目的信息和依赖关系
{ "name": "socket-chat-example", "version": "0.0.1", "description": "my first socket.io app", "dependencies": {}
}编写index.js -服务端代码
//使用express模块快速搭建web服务器var express = require('express');var app = express();var http = require('http').Server(app);//使用socket.io监听事件var io = require('socket.io')(http);//使用express发送css js等静态资源app.use(express.static('public'));//express获得GET请求时将index.html文件返回给浏览器app.get('/',function(req,res){
res.sendFile(__dirname + '/index.html');
});//socket监听连接事件io.on('connection', function(socket){ console.log('一个用户上线了'); //socket监听失去连接的事件
socket.on('disconnect', function(){ console.log('一个用户下线了');
});//当socket监听到了'chat message'事件
socket.on('chat message', function(msg){ //将收到的信息返回给所有客户端
io.emit('chat message',msg);
});
});//服务器监听端口3000http.listen(3000,function(){ console.log('listening on *:3000');
})cd到当前目录,并在命令行用npm安装express和socket.io
编写index.html
<!doctype html><html>
<head>
<title>Socket.IO chat</title>
<style>
* { 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>
<script src="/socket.io/socket.io.js"></script>
<script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
<script>
var socket = io();
$('form').submit(function(){ //点击发送按钮,提交输入的信息
socket.emit('chat message', $('#m').val());
$('#m').val(''); return false;
}); //接收到chat message时
socket.on('chat message', function(msg){ //将chat message显示在页面
$('#messages').append($('<li>').text(msg));
}); </script>
</body></html>最后,在命令行中输入node index.js 在浏览器上输入http://localhost:3030 就可以开始多窗口聊天啦!
作者:亲爱的村姑
链接:https://www.jianshu.com/p/5539ccd8d9c4