php实现推送消息
PHP 实现推送消息的方法
使用 WebSocket 实现实时推送
WebSocket 是一种在单个 TCP 连接上进行全双工通信的协议,适合实现实时消息推送。
安装 Ratchet 库(WebSocket 实现):
composer require cboden/ratchet
创建 WebSocket 服务器:
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();
客户端连接代码:

const socket = new WebSocket('ws://localhost:8080/push');
socket.onmessage = function(e) {
console.log('收到消息:', e.data);
};
使用 Server-Sent Events (SSE)
SSE 允许服务器向客户端推送事件,适合单向消息推送场景。
服务器端实现:
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
function sendMessage($id, $message) {
echo "id: $id\n";
echo "data: $message\n\n";
ob_flush();
flush();
}
while(true) {
$time = date('r');
sendMessage(time(), "服务器时间: {$time}");
sleep(1);
}
客户端实现:

const eventSource = new EventSource('sse.php');
eventSource.onmessage = function(e) {
console.log('新消息:', e.data);
};
使用第三方推送服务
Firebase Cloud Messaging (FCM) 实现:
function sendFCM($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;
}
使用长轮询技术
实现简单的长轮询机制:
// 服务器端
$lastEventId = $_SERVER['HTTP_LAST_EVENT_ID'] ?? 0;
while(true) {
$newData = checkForNewData($lastEventId);
if($newData) {
header('Content-Type: application/json');
echo json_encode($newData);
exit;
}
sleep(1);
}
// 客户端
function longPoll() {
fetch('poll.php')
.then(response => response.json())
.then(data => {
processData(data);
longPoll();
});
}
使用消息队列系统
结合 RabbitMQ 实现消息推送:
// 生产者
$connection = new AMQPConnection([
'host' => 'localhost',
'port' => 5672,
'login' => 'guest',
'password' => 'guest'
]);
$connection->connect();
$channel = new AMQPChannel($connection);
$exchange = new AMQPExchange($channel);
$exchange->publish('消息内容', 'routing_key');
// 消费者
$queue = new AMQPQueue($channel);
$queue->setName('queue_name');
$queue->consume(function(AMQPEnvelope $envelope) {
echo $envelope->getBody();
return false; // 返回false以ack消息
});
每种方法适用于不同场景:WebSocket 适合实时双向通信,SSE 适合服务器向客户端推送,第三方服务适合移动端推送,长轮询兼容性最好但效率较低,消息队列适合分布式系统。






