版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/maindek/article/details/82885420
socket.io 一个与服务器实时通信的工具,它与原生的webSocket相比,具有更可靠、快速的优点,并且能很好的兼容不同系统、浏览器及设备。http://socket.io/
nodeJS 服务端js解析引擎 http://www.nodejs.org/
一、环境搭建
在服务器上创建目录socketio,以它为我们的工作空间。
安装node(略过)
在工作空间下:
安装socket io模块,
npm install --save socket.io
安装完之后可以看到多一个node_modules目录,里面有刚才所安装的socket.io内容
安装express
express 是一个基于node的web框架
npm install --save [email protected]
可以看到 express到了node_modules目录下
二,建立socket服务器
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(__dirname + '/index.html');
});
// 测试链接
// io.on('connection', function(socket){
// console.log('a user connected');
// });
// 检测断开链接
// io.on('connection', function(socket){
// console.log('a user connected');
// socket.on('disconnect', function(){
// console.log('user disconnected');
// });
// });
// 接收信息
// io.on('connection', function(socket){
// socket.on('chat message', function(msg){
// console.log('message: ' + msg);
// });
// });
// 广播给所有人信息
// 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);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
客户端测试:
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="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
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>
</body>
</html>
客户端监听服务端发送来的msg消息,同时也向服务端发送一个msg消息。
服务器监听客户端发送来的msg消息,同时也向客户端发送接收到的msg消息。
此时多用户登录就如同在同一个房间聊天
启动服务器
node index.js
此案例摘自官方案例