PHP http长连接的实现
PHP HTTP 长连接的实现
HTTP 长连接(Keep-Alive)允许客户端和服务器在单个TCP连接上发送和接收多个HTTP请求/响应,减少连接建立和关闭的开销。以下是实现方法:
启用服务器端Keep-Alive
在Apache或Nginx中配置Keep-Alive参数:
Apache配置(httpd.conf或.htaccess)
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 15
Nginx配置
keepalive_timeout 60s;
keepalive_requests 100;
PHP脚本处理长连接
通过设置响应头明确启用Keep-Alive:
header('Connection: keep-alive');
header('Keep-Alive: timeout=60, max=100');
流式输出(chunked transfer)
对于长时间运行的脚本,使用分块传输编码逐步输出内容:
header('Content-Type: text/html');
header('Transfer-Encoding: chunked');
ob_flush();
flush();
while ($data = getStreamData()) {
echo chunk_encode($data);
ob_flush();
flush();
sleep(1);
}
避免脚本超时
调整PHP执行时间限制:
set_time_limit(0); // 取消时间限制
ignore_user_abort(true); // 忽略客户端断开
WebSocket替代方案
对于需要双向实时通信的场景,建议使用WebSocket:
// 使用Ratchet库示例
$app = new Ratchet\App('localhost', 8080);
$app->route('/chat', new MyChatServer);
$app->run();
注意事项
- 长连接会占用服务器资源,需合理设置超时时间
- 负载均衡环境下可能需要特殊配置
- 客户端可能主动关闭连接,需做好错误处理
- 考虑使用心跳机制检测连接状态






