php如何实现推送消息推送消息
PHP 实现消息推送的方法
使用 WebSocket 实现实时推送
WebSocket 是一种全双工通信协议,适合实时推送消息。PHP 可以与 WebSocket 服务器(如 Ratchet)结合使用。
安装 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();
客户端连接代码(JavaScript):
const socket = new WebSocket('ws://localhost:8080');
socket.onmessage = function(event) {
console.log('Message received:', event.data);
};
使用 Server-Sent Events (SSE)
SSE 是一种基于 HTTP 的轻量级推送技术,适合单向实时通信。
PHP 服务端代码:
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
while (true) {
$data = json_encode(['message' => 'New update']);
echo "data: {$data}\n\n";
ob_flush();
flush();
sleep(1);
}
客户端代码(JavaScript):

const eventSource = new EventSource('sse.php');
eventSource.onmessage = function(event) {
console.log('New message:', event.data);
};
使用第三方推送服务
Firebase Cloud Messaging (FCM) 是一种流行的跨平台推送服务。
发送 FCM 消息的 PHP 代码:
$url = 'https://fcm.googleapis.com/fcm/send';
$serverKey = 'YOUR_SERVER_KEY';
$token = 'DEVICE_TOKEN';
$data = [
'to' => $token,
'notification' => [
'title' => 'New Message',
'body' => 'You have a new notification'
]
];
$options = [
'http' => [
'header' => "Content-type: application/json\r\nAuthorization: key=$serverKey\r\n",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo $result;
使用长轮询技术
长轮询是一种模拟实时推送的替代方案,客户端定期向服务器请求新消息。
PHP 服务端代码:

$lastEventId = $_GET['lastEventId'] ?? 0;
while (true) {
$newEvents = checkForNewEvents($lastEventId);
if (!empty($newEvents)) {
echo json_encode($newEvents);
break;
}
sleep(1);
}
客户端代码(JavaScript):
function longPoll() {
fetch('poll.php?lastEventId=' + lastEventId)
.then(response => response.json())
.then(data => {
console.log('New events:', data);
longPoll();
});
}
longPoll();
使用消息队列系统
对于高并发场景,可以结合 RabbitMQ 或 Redis 等消息队列系统实现推送。
使用 Redis 发布/订阅的 PHP 示例:
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
// 发布消息
$redis->publish('notifications', json_encode(['message' => 'Hello']));
客户端需要通过 WebSocket 或其他实时技术订阅 Redis 频道。
以上方法各有优缺点,选择时应考虑项目需求、技术栈和性能要求。WebSocket 适合需要双向通信的场景,SSE 适合服务器向客户端的单向推送,第三方服务适合跨平台需求,长轮询兼容性最好但效率较低,消息队列适合高并发系统。






