php实现推送
PHP 实现推送功能的方法
PHP 实现推送功能可以通过多种方式完成,包括 WebSocket、Server-Sent Events (SSE)、长轮询或第三方推送服务。以下是几种常见的方法:
使用 WebSocket 实现实时推送
WebSocket 是一种全双工通信协议,适合实现实时推送功能。PHP 可以通过 Ratchet 库实现 WebSocket 服务器。
安装 Ratchet:
composer require cboden/ratchet
创建 WebSocket 服务器:
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();
创建 Chat 类处理消息:
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
}
public function onMessage(ConnectionInterface $from, $msg) {
foreach ($this->clients as $client) {
$client->send($msg);
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
}
public function onError(ConnectionInterface $conn, \Exception $e) {
$conn->close();
}
}
前端连接 WebSocket:
const socket = new WebSocket('ws://localhost:8080');
socket.onmessage = function(event) {
console.log('Message from server:', event.data);
};
使用 Server-Sent Events (SSE)
SSE 是一种基于 HTTP 的单向通信协议,适合服务器向客户端推送数据。
PHP 实现 SSE:
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
while (true) {
$data = json_encode(['time' => date('H:i:s')]);
echo "data: {$data}\n\n";
ob_flush();
flush();
sleep(1);
}
前端接收 SSE:
const eventSource = new EventSource('sse.php');
eventSource.onmessage = function(event) {
console.log('New message:', event.data);
};
使用长轮询 (Long Polling)
长轮询是一种模拟实时推送的技术,客户端发送请求后,服务器保持连接直到有新数据。
PHP 实现长轮询:
$lastUpdate = $_GET['lastUpdate'] ?? 0;
while (true) {
$newData = checkForNewData($lastUpdate);
if ($newData) {
echo json_encode($newData);
break;
}
sleep(1);
}
前端发起长轮询请求:
function poll() {
fetch('poll.php?lastUpdate=' + lastUpdate)
.then(response => response.json())
.then(data => {
console.log('New data:', data);
poll();
});
}
poll();
使用第三方推送服务
Firebase Cloud Messaging (FCM) 或 Pusher 等第三方服务可以简化推送实现。
使用 FCM 发送推送:
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = [
'Authorization: key=YOUR_SERVER_KEY',
'Content-Type: application/json'
];
$data = [
'to' => '/topics/news',
'notification' => [
'title' => 'New Message',
'body' => 'Hello World!'
]
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($ch);
curl_close($ch);
注意事项
- WebSocket 需要 PHP 常驻内存运行,适合高实时性场景。
- SSE 和长轮询基于 HTTP,适合简单推送需求。
- 第三方推送服务适合跨平台或大规模推送场景。
- 确保服务器配置支持长时间运行的脚本(如
set_time_limit(0))。





