一个 node.js + socket.io 示例
添加依赖
1 2 3
| np init -y npm i express socket.io body-parser -S -D npm start
|
目录结构
1 2 3 4 5 6 7 8 9
| ├── app.js ├── public │ ├── css │ │ └── style.css │ └── js │ ├── index.js │ └── vue.js └── views └── index.html
|
配置服务 app.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| const http = require("http"); const fs = require("fs"); const path = require("path"); const express = require('express'); const app = express(); const server = require('http').createServer(app); const io = require('socket.io')(server);
....
....
const port = 3000; server.listen(port, err => { console.log(err ? 'Server Error' : `http://localhost:${port}`); });
|
路由配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| const readFile = filePath => { return new Promise((resolve, reject) => { fs.readFile(path.join(__dirname, filePath), 'utf-8', (err, data) => { err ? reject(err) : resolve(data); }); }); };
app.use(express.static(path.join(__dirname, '/')));
app.get('/', (req, res) => { readFile('./views/index.html').then(data => { res.send(data); }); });
app.use((req, res, next) => { res.send("<h1>页面找不到了!<a href='/'>点我</a>回家!</h1>"); });
|
主角 socket.io (服务端)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| io.on('connection', socket => { console.log('用户连接', socket.request.headers.cookie); });
socket.on('hi', data => { console.log(`用户发送:${data}`); });
socket.emit('back_hi', `服务器:${Date.now()}!`);
socket.broadcast.emit('back_hi', data);
socket.on('disconnect', data => { console.log('断开', data); });
|
index.html (客户端)
1 2 3 4 5 6 7 8 9 10
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <script src="./socket.io/socket.io.js"></script> <title>node_demo</title> </head> <body></body> <script src="./public/js/index.js "></script> </html>
|
index.js
1 2 3 4 5 6 7 8
| socket = io.connect();
ocket.emit('hi', '你好');
socket.on('back_hi', msg => { console.log(msg); });
|
注意事项
- 配置 app.js 的顺序不要错
- 一定要开启公共路径
- 配置根路径一定要读取文件发送客户端响应