WebSocket 库 Ratchet for PHP:在网站上创建实时功能

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

什么是 WebSocket,为什么需要 Ratchet 库 for PHP?

WebSocket 是一种协议,可在客户端(浏览器)和服务器之间建立持久的双向连接。与传统的 HTTP 不同(HTTP 中只有客户端发起请求),WebSocket 允许服务器即时发送数据,无需等待请求。这是聊天、实时通知、在线游戏、追踪器以及任何对低延迟有要求的应用的理想解决方案。

标准的 PHP 没有内置的 WebSocket 支持,但 Ratchet 库(使用 ReactPHP 组件)填补了这一空白。Ratchet 是一个异步库,允许直接从 PHP 运行 WebSocket 服务器,同时处理多个连接而不会阻塞。



Ratchet 的主要功能

  • 异步 — 基于 ReactPHP,在等待数据时不阻塞线程。
  • 协议支持 — WebSocket (RFC 6455),以及 HTTP 组件(用于混合应用)。
  • 简单易用 — 启动服务器只需最少的代码。
  • 可扩展性 — 可与 ZeroMQ 或 Redis 结合,用于集群环境。
  • 兼容性 — 通过内置的 WebSocket 对象与所有现代浏览器兼容。


安装 Ratchet

通过 Composer 进行安装。在项目根目录打开终端并执行:

composer require cboden/ratchet

安装后,vendor 文件夹中将出现所有依赖项,包括 ReactPHP。



使用 Ratchet 创建一个简单的 WebSocket 服务器

创建文件 server.php:

<?phprequire 'vendor/autoload.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 "新连接: {$conn->resourceId}"; }

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 "断开连接: {$conn->resourceId}"; }

public function onError(ConnectionInterface $conn, \\Exception $e) { echo "错误: {$e->getMessage()}"; $conn->close(); }}

$server = IoServer::factory( new HttpServer( new WsServer( new Chat() ) ), 8080);

echo "服务器已在端口 8080 上启动";$server->run();


代码说明

  • Chat — 实现 MessageComponentInterface 的类。在 onOpen 中保存连接,在 onMessage 中向除发送者外的所有客户端广播消息。
  • IoServer::factory — 基于 ReactPHP 创建服务器。我们将组件包装在 WsServer(用于 WebSocket)和 HttpServer(用于兼容 HTTP 请求)中。
  • 服务器监听端口 8080。使用命令启动它:php server.php。


客户端部分 (JavaScript)

创建 HTML 文件 client.html:

<!DOCTYPE html><html><head>    <title>WebSocket 聊天</title>    <script>        const ws = new WebSocket('ws://localhost:8080');

推荐