用Node.js和Socket.IO实现实时通信应用

用Node.js和Socket.IO实现实时通信应用

引言

实时通信是现代Web应用的核心需求,如聊天、通知等。Socket.IO是Node.js的WebSocket库,简化了双向通信。本文将指导你用Node.js和Socket.IO实现一个实时聊天应用。

环境搭建

安装依赖:npm install express socket.io

后端实现

server.js中设置Socket.IO服务器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = new Server(server);

app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
console.log('用户连接:', socket.id);
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
socket.on('disconnect', () => {
console.log('用户断开:', socket.id);
});
});

server.listen(8080, () => {
console.log('服务器运行在 http://localhost:8080');
});

前端实现

index.html中添加Socket.IO客户端:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html>
<head>
<title>实时聊天</title>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<ul id="messages"></ul>
<input id="input" autocomplete="off" /><button>发送</button>
<script>
const socket = io();
const messages = document.getElementById('messages');
const input = document.getElementById('input');

document.querySelector('button').onclick = () => {
if (input.value) {
socket.emit('chat message', input.value);
input.value = '';
}
};

socket.on('chat message', (msg) => {
const li = document.createElement('li');
li.textContent = msg;
messages.appendChild(li);
});
</script>
</body>
</html>

部署注意事项

  • CORS配置:确保Socket.IO支持跨域请求。
  • 扩展性:使用socket.io-redis实现多实例扩展。
  • 安全性:验证用户身份,避免未经授权的连接。

总结

Socket.IO为Node.js应用提供了简单高效的实时通信方案。通过本文的示例,你可以快速搭建一个实时聊天应用。结合CORS和扩展性配置,可进一步提升应用健壮性。