php实现推送功能实现原理
PHP 实现推送功能的原理
推送功能的核心在于服务器主动向客户端发送数据,而非传统的客户端请求-服务器响应模式。以下是几种常见的实现方式及其原理:
轮询(Polling)
客户端定期向服务器发送请求检查是否有新数据。虽然实现简单,但效率较低。
// 客户端JavaScript示例
setInterval(function() {
fetch('check_updates.php')
.then(response => response.json())
.then(data => {
if (data.update) {
// 处理更新
}
});
}, 5000);
长轮询(Long Polling)
客户端发送请求后,服务器保持连接打开直到有新数据或超时。减少无效请求,但服务器资源消耗较大。
// 服务器端PHP示例
while (true) {
$newData = checkForUpdates();
if ($newData) {
echo json_encode(['update' => true, 'data' => $newData]);
break;
}
sleep(1);
// 超时处理
if (time() - $startTime > 30) {
echo json_encode(['update' => false]);
break;
}
}
WebSocket
全双工通信协议,适合实时性要求高的场景。需要服务器支持WebSocket协议。
// 使用Ratchet库实现WebSocket服务器
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class PushServer 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) {
// 错误处理
}
}
$server = IoServer::factory(
new HttpServer(new WsServer(new PushServer())),
8080
);
$server->run();
Server-Sent Events (SSE)
基于HTTP的单向通信,服务器可以推送数据到客户端。适合不需要双向通信的场景。
// 服务器端PHP示例
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
while (true) {
$newData = getUpdates();
if ($newData) {
echo "data: " . json_encode($newData) . "\n\n";
ob_flush();
flush();
}
sleep(1);
}
第三方推送服务
使用如Firebase Cloud Messaging (FCM)、Apple Push Notification Service (APNS)等第三方服务实现跨平台推送。
// 使用FCM发送推送通知
function sendFCMNotification($token, $message) {
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = [
'Authorization: key=YOUR_SERVER_KEY',
'Content-Type: application/json'
];
$data = [
'to' => $token,
'notification' => [
'title' => 'New Message',
'body' => $message
]
];
$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);
return $result;
}
选择建议
- 简单场景:使用长轮询或SSE
- 高实时性需求:WebSocket
- 移动端推送:第三方服务如FCM/APNS
- 跨平台支持:考虑第三方服务或WebSocket
每种方法都有其适用场景和优缺点,应根据具体需求选择最合适的实现方式。







