php实现推送
PHP 实现推送功能的方法
使用 WebSocket 实现实时推送
WebSocket 是一种在单个 TCP 连接上进行全双工通信的协议,适合实现实时推送功能。
// 服务端代码示例(使用 Ratchet 库)
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class PushServer 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();
}
}
// 启动服务器
$app = new Ratchet\App('localhost', 8080);
$app->route('/push', new PushServer);
$app->run();
客户端可以使用 JavaScript 连接 WebSocket 接收推送消息。
使用 Server-Sent Events (SSE)
SSE 是一种服务器向客户端推送数据的轻量级技术。
// 服务端代码
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
while (true) {
$data = getNewData(); // 获取新数据
echo "data: " . json_encode($data) . "\n\n";
ob_flush();
flush();
sleep(1);
}
客户端使用 EventSource API 接收推送:
const eventSource = new EventSource('push.php');
eventSource.onmessage = function(e) {
console.log(e.data);
};
使用第三方推送服务
对于移动端推送,可以使用 Firebase Cloud Messaging (FCM) 或 Apple Push Notification Service (APNS)。
FCM 推送示例:
function sendFCMPush($token, $title, $body) {
$url = 'https://fcm.googleapis.com/fcm/send';
$serverKey = 'YOUR_SERVER_KEY';
$notification = [
'title' => $title,
'body' => $body,
'sound' => 'default'
];
$fields = [
'to' => $token,
'notification' => $notification,
'priority' => 'high'
];
$headers = [
'Authorization: key=' . $serverKey,
'Content-Type: application/json'
];
$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($fields));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
使用长轮询技术
长轮询是一种模拟实时推送的技术,客户端发送请求后,服务器保持连接直到有新数据。
// 长轮询服务端代码
$timeout = 30; // 超时时间
$start = time();
while (true) {
$data = checkForNewData(); // 检查新数据
if ($data !== false || (time() - $start) > $timeout) {
echo json_encode($data ? $data : ['timeout' => true]);
break;
}
usleep(500000); // 暂停0.5秒
}
使用消息队列
对于高并发场景,可以使用消息队列系统如 RabbitMQ 或 Redis 实现推送。
Redis 发布/订阅示例:
// 发布消息
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->publish('notification_channel', json_encode(['message' => 'Hello']));
// 订阅消息(通常运行在单独进程)
$redis->subscribe(['notification_channel'], function($redis, $channel, $message) {
echo "Received: $message\n";
});
每种方法都有其适用场景,选择哪种技术取决于项目需求、性能要求和目标平台。






