<?php
// WebSocket 服务器示例代码
// 引入必要的类库
require 'vendor/autoload.php';
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
// 创建一个简单的 WebSocket 组件
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} has disconnected\n";
}
// 当发生错误时调用
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
// 设置并启动 WebSocket 服务器
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
$server = IoServer::factory(
new HttpServer(new WsServer(new Chat())),
8080
);
$server->run();
?>
引入类库:使用 Ratchet 库来创建 WebSocket 服务器。你需要通过 Composer 安装这个库,命令是 composer require cboden/ratchet。
创建 WebSocket 组件:定义一个 Chat 类,它实现了 MessageComponentInterface 接口,用于处理 WebSocket 连接、消息接收和发送等事件。
事件处理方法:
onOpen:当有新客户端连接时调用。onMessage:当接收到客户端消息时调用,并将消息广播给所有其他客户端。onClose:当客户端断开连接时调用。onError:当发生错误时调用。启动 WebSocket 服务器:使用 IoServer、HttpServer 和 WsServer 来设置并启动 WebSocket 服务器,监听端口 8080。
运行服务器:最后调用 $server->run() 启动 WebSocket 服务器。
这个示例展示了如何使用 PHP 创建一个简单的 WebSocket 聊天服务器。
上一篇:php array_slice
下一篇:php 二维数组排序
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站