1.搭建项目
mkdir server-demo //创建文件夹
cd server-demo //打开文件夹
yarn add socket.io 或者 npm install socket.io // 安装socket.io
2. 创建server.js
const content = require('fs').readFileSync(__dirname + '/index.html', 'utf8');
const httpServer = require('http').createServer((req, res) => {
// serve the index.html file
res.setHeader('Content-Type', 'text/html');
res.setHeader('Content-Length', Buffer.byteLength(content));
res.end(content);
});
const io = require('socket.io')(httpServer);
/**
* 监听了用户连接事件
* socket表示用户的连接
* socket.emit 表示触发某个事件,如果需要给浏览器发数据,需要触发浏览器注册的某个事件
* socket.on 表示注册某个事件,如果我需要获取浏览器的数据,需要注册一个事件,等待浏览器触发
*/
io.on('connect', socket => {
console.log('新用户连接了');
// socket.emit 方法表示给浏览器发送数据
// 参数1:事件的名字
socket.emit('send', {name: 'zs'})
// 事件名:任意
socket.on('hehe', data => {
console.log(data);
socket.emit('send', data)
})
});
httpServer.listen(3000, () => {
console.log('go to http://localhost:3000');
});
3.创建html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>socket.io</title>
</head>
<body>
hello
<ul id="events"></ul>
<script src="/socket.io/socket.io.js"></script>
<script>
// 连接socket服务
// 参数:服务器地址
const socket = io('http://localhost:3000');
// 接受服务器返回的数据
socket.on('send', data => {
console.log(data);
})
// 注册一个事件
socket.emit('hehe', {name: 'li', age: 28})
</script>
</body>
</html>
4.启动socket.io服务 node ./server.js
5.浏览器打开地址: http://localhost:3000
socke.io记住2个点
1.想要拿数据,就监听一个事件
2.想要发数据,就触发某个方法