php 实现长连接
使用 header() 函数实现长连接
在 PHP 中,可以通过设置 HTTP 头信息 Connection: keep-alive 和 Keep-Alive: timeout=x, max=y 来实现长连接。示例代码如下:
header("Connection: keep-alive");
header("Keep-Alive: timeout=60, max=1000");
timeout=60表示连接保持 60 秒。max=1000表示最多允许 1000 次请求复用同一个连接。
使用 ob_flush() 和 flush() 保持连接
在长连接场景下(如实时数据推送),可以使用输出缓冲机制保持连接不中断:
// 关闭输出缓冲
if (ob_get_level() > 0) {
ob_end_flush();
}
// 推送数据
while (true) {
echo "Data: " . date("Y-m-d H:i:s") . "\n";
ob_flush();
flush();
sleep(1); // 每秒推送一次
}
结合 WebSocket 实现持久连接
PHP 原生不支持 WebSocket,但可以通过以下方式实现:
-
使用
Ratchet库(推荐):
安装 Ratchet:composer require cboden/ratchet示例服务端代码:
use Ratchet\Server\IoServer; use Ratchet\Http\HttpServer; use Ratchet\WebSocket\WsServer; use MyApp\Chat; // 自定义处理类 require dirname(__DIR__) . '/vendor/autoload.php'; $server = IoServer::factory( new HttpServer(new WsServer(new Chat())), 8080 ); $server->run(); -
自定义 WebSocket 处理类:
namespace MyApp; use Ratchet\MessageComponentInterface; use Ratchet\ConnectionInterface; class Chat implements MessageComponentInterface { public function onOpen(ConnectionInterface $conn) { // 新连接逻辑 } public function onMessage(ConnectionInterface $from, $msg) { // 处理消息 } public function onClose(ConnectionInterface $conn) { // 连接关闭逻辑 } public function onError(ConnectionInterface $conn, \Exception $e) { // 错误处理 } }
使用 fsockopen 实现 TCP 长连接
适用于非 HTTP 协议的持久连接:

$socket = fsockopen("tcp://example.com", 8080, $errno, $errstr, 30);
if (!$socket) {
die("Failed: $errstr ($errno)");
}
// 发送数据
fwrite($socket, "PING\n");
// 接收响应
while (!feof($socket)) {
echo fgets($socket, 128);
}
fclose($socket);
注意事项
- Nginx/Apache 配置:确保服务器支持长连接(如 Nginx 的
keepalive_timeout)。 - 资源消耗:长连接会占用服务器资源,需合理设置超时和最大请求数。
- WebSocket:需依赖外部库或扩展(如
Ratchet或Swoole)。
以上方法可根据实际场景选择,HTTP 长连接适合短时复用,WebSocket 适合实时双向通信。






