js实现长连接
实现长连接的常见方法
在JavaScript中,实现长连接通常用于实时通信场景,如聊天应用、实时数据更新等。以下是几种主流方法:
WebSocket
WebSocket是HTML5提供的协议,支持全双工通信,适合需要频繁交互的场景。
const socket = new WebSocket('ws://your-server-url');
socket.onopen = function() {
console.log('连接已建立');
socket.send('Hello Server!');
};
socket.onmessage = function(event) {
console.log('收到消息: ' + event.data);
};
socket.onclose = function() {
console.log('连接关闭');
};
Server-Sent Events (SSE)
SSE是单向通信,适合服务器向客户端推送数据的场景。
const eventSource = new EventSource('/sse-endpoint');
eventSource.onmessage = function(event) {
console.log('收到数据: ', event.data);
};
eventSource.onerror = function() {
console.error('连接错误');
};
轮询(Polling)
通过定时请求实现简单长连接效果。
function poll() {
fetch('/api/check-updates')
.then(response => response.json())
.then(data => {
console.log(data);
setTimeout(poll, 5000); // 5秒后再次请求
});
}
poll();
长轮询(Long Polling)
服务器在有数据时才响应请求,减少无效请求。

function longPoll() {
fetch('/api/long-poll')
.then(response => response.json())
.then(data => {
console.log(data);
longPoll(); // 立即发起下一次请求
})
.catch(() => {
setTimeout(longPoll, 5000); // 出错时延迟重试
});
}
longPoll();
实现注意事项
- WebSocket需要服务器支持WS协议
- SSE不支持IE浏览器
- 轮询会增加服务器负担
- 所有方法都应考虑错误处理和重连机制
- 生产环境建议使用成熟的库如Socket.IO
性能优化建议
- 合理设置心跳机制保持连接活跃
- 考虑使用二进制数据减少传输量
- 实现连接状态监控和自动重连
- 在移动端注意网络切换时的连接处理






