php如何实现推送消息推送消息
PHP 实现消息推送的方法
使用 WebSocket 实现实时推送
WebSocket 是一种在单个 TCP 连接上进行全双工通信的协议,适合实现实时消息推送。
// 服务器端代码示例(使用 Ratchet 库)
require 'vendor/autoload.php';
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();
}
}
$server = new \Ratchet\App('localhost', 8080);
$server->route('/push', new PushServer);
$server->run();
使用 Server-Sent Events (SSE)
SSE 允许服务器向客户端推送事件,适合单向实时通信。

// PHP 服务器端代码
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);
}
使用第三方推送服务
Firebase Cloud Messaging (FCM) 和 Pusher 等第三方服务提供成熟的推送解决方案。

// 使用 FCM 发送推送通知
function sendFCMNotification($token, $message) {
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = [
'to' => $token,
'notification' => [
'title' => '新消息',
'body' => $message
]
];
$headers = [
'Authorization: key=YOUR_SERVER_KEY',
'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;
}
使用长轮询技术
长轮询是传统轮询的改进版本,服务器在有数据时才响应。
// PHP 长轮询实现
function longPolling() {
$timeout = 30;
$start = time();
while (true) {
if (hasNewData()) {
return getNewData();
}
if (time() - $start > $timeout) {
return null;
}
usleep(100000); // 等待100毫秒
}
}
使用消息队列
RabbitMQ 或 Redis 等消息队列系统可以高效处理消息推送。
// 使用 Redis 发布/订阅
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
// 发布消息
$redis->publish('channel_name', json_encode(['message' => 'Hello']));
选择哪种方法取决于具体需求:WebSocket 适合双向实时通信,SSE 适合服务器到客户端的单向推送,第三方服务提供完整的解决方案,长轮询适合简单场景,消息队列适合高并发系统。






