php实现推送消息推送消息
PHP 实现消息推送的方法
使用 WebSocket 实现实时推送
WebSocket 是一种在单个 TCP 连接上进行全双工通信的协议,适合实现实时消息推送。PHP 可以通过 Ratchet 库实现 WebSocket 服务端。
安装 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();
实现 Chat 类:
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat 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-Sent Events (SSE)
SSE 是一种服务器向浏览器推送消息的轻量级技术,基于 HTTP 协议。
PHP 实现 SSE 服务端:

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
function sendMsg($id, $msg) {
echo "id: $id" . PHP_EOL;
echo "data: $msg" . PHP_EOL;
echo PHP_EOL;
ob_flush();
flush();
}
while(true) {
$serverTime = time();
sendMsg($serverTime, 'server time: ' . date("h:i:s", $serverTime));
sleep(1);
}
客户端 JavaScript 代码:
const evtSource = new EventSource("sse.php");
evtSource.onmessage = function(e) {
console.log(e.data);
};
使用第三方推送服务
Firebase Cloud Messaging (FCM) 是 Google 提供的跨平台消息推送服务。
发送 FCM 通知的 PHP 代码:

function sendFCMNotification($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;
}
使用长轮询技术
长轮询是一种模拟实时通信的技术,客户端发送请求后服务器保持连接直到有数据可返回。
PHP 长轮询实现:
// 服务器端 longpoll.php
$timeout = 30;
$start = time();
while(true) {
// 检查是否有新消息
if(hasNewMessages()) {
echo json_encode(getMessages());
break;
}
// 检查超时
if(time() - $start > $timeout) {
echo json_encode([]);
break;
}
usleep(100000); // 100ms
}
// 客户端 JavaScript
function longPoll() {
fetch('longpoll.php')
.then(response => response.json())
.then(data => {
if(data.length > 0) {
// 处理新消息
console.log(data);
}
longPoll(); // 再次发起请求
});
}
longPoll();
使用 MQTT 协议
MQTT 是轻量级的发布/订阅消息协议,适合物联网和移动应用。
PHP 使用 MQTT 发布消息:
require __DIR__ . '/vendor/autoload.php';
use PhpMqtt\Client\MqttClient;
$server = 'broker.hivemq.com';
$port = 1883;
$clientId = 'php-publisher';
$topic = 'test/topic';
$mqtt = new MqttClient($server, $port, $clientId);
$mqtt->connect();
$mqtt->publish($topic, 'Hello from PHP!', 0);
$mqtt->disconnect();
每种方法都有其适用场景:WebSocket 适合高频率双向通信,SSE 适合服务器向客户端的单向推送,FCM 适合移动应用推送,长轮询适合简单场景,MQTT 适合物联网和低带宽环境。






