使用Ratchet库可实现PHP的WebSocket实时通信。首先通过Composer安装Ratchet及ReactPHP依赖,然后创建实现MessageComponentInterface接口的Chat类,处理连接、消息收发与异常。启动IoServer监听8080端口,前端用JavaScript建立WebSocket连接并收发消息。为实现PHP脚本主动推送,推荐使用Redis Pub/Sub:在Chat类中集成Predis,通过事件循环定期监听Redis频道,外部PHP脚本通过lpush向频道发送消息,Ratchet服务捕获后广播给所有客户端。也可采用ZeroMQ或本地Socket通信替代。注意Ratchet为单进程,生产环境需结合Nginx反向代理、防火墙开放端口,并防范内存泄漏。

PHP 实现 WebSocket 实时通信,关键在于使用合适的库来维持长连接。Ratchet 是一个流行的 PHP 库,允许你创建 WebSocket 服务端,实现客户端与服务器之间的双向实时通信。下面介绍如何用 Ratchet 搭建一个简单的 WebSocket 服务,并从 PHP 脚本中调用或与之交互。
Ratchet 是一个用于构建实时 Web 应用的 PHP 库,支持 WebSocket 协议。它基于 ReactPHP 构建,能够处理异步连接,适合聊天应用、通知系统等需要实时推送的场景。
使用 Composer 安装 Ratchet:
composer require ratchet/rfc6455 composer require react/socket composer require react/http
这会安装核心组件,包括 WebSocket 处理和底层事件循环支持。
立即学习“PHP免费学习笔记(深入)”;
创建一个名为 websocket_server.php 的文件:
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
foreach ($this->clients as $client) {
if ($from !== $client) {
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} closed\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "Error: {$e->getMessage()}\n";
$conn->close();
}
}
// 启动 WebSocket 服务
$server = IoServer::factory(
new HttpServer(new WsServer(new Chat())),
8080
);
echo "WebSocket server started on port 8080...\n";
$server->run();
运行此脚本:
php websocket_server.php
服务将在 ws://localhost:8080 监听连接。
在浏览器中测试连接:
const conn = new WebSocket('ws://localhost:8080');
conn.onopen = function(e) {
console.log("Connected");
conn.send("Hello Server!");
};
conn.onmessage = function(e) {
console.log("Received: " + e.data);
};
这样,任意客户端发送消息,其他客户端都能收到(除自己外)。
由于 WebSocket 是长连接,PHP CLI 脚本无法直接“调用”某个连接,但可以通过以下方式实现消息推送:
方案一:使用共享数据通道(如 Redis Pub/Sub)示例:集成 Redis 到 Ratchet
use Predis\Client;
class Chat implements MessageComponentInterface {
protected $clients;
private $redis;
public function __construct() {
$this->clients = new \SplObjectStorage;
$this->redis = new Client();
$this->listenRedis();
}
private function listenRedis() {
$loop = \React\EventLoop\Factory::create();
$loop->addPeriodicTimer(0.1, function() {
$msg = $this->redis->brpop('websocket:messages', 1);
if ($msg) {
foreach ($this->clients as $client) {
$client->send($msg[1]);
}
}
});
$loop->run();
}
// ... onOpen, onMessage 等方法保持不变
}
然后从普通 PHP 脚本发送消息:
$redis = new Predis\Client();
$redis->lpush('websocket:messages', 'Hi from PHP script!');
以上就是如何实现PHP调用实时通信WebSocket服务_PHP实时通信WebSocket服务实现与Ratchet教程的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号