Files
shop-platform/docs/websocket/test_websocket.php

73 lines
2.2 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
/**
* WebSocket 服务器 PHP 客户端测试脚本
* 用于测试 WebSocket 服务器的连接和基本功能
*
* 使用方法php test_websocket.php
* 注意:需要先启动 WebSocket 服务器 (php ws_server.php)
*/
use Ratchet\Client\WebSocket;use React\EventLoop\Factory;
use React\Socket\Connector;
use Ratchet\RFC6455\Messaging\MessageInterface;
require __DIR__ . '/../../src/vendor/autoload.php';
// WebSocket 服务器地址
$wsUrl = 'ws://localhost:8080/ws'; // 默认测试路径
// $wsUrl = 'ws://localhost:8080/ws/aikefu'; // aikefu 插件路径
echo "正在连接到 WebSocket 服务器: {$wsUrl}\n";
// 创建事件循环
$loop = Factory::create();
// 创建连接
$connector = new Connector($loop);
// 连接到 WebSocket 服务器
$connector($wsUrl)
->then(function ($conn) use ($loop) {
echo "✅ 成功连接到 WebSocket 服务器\n";
// 创建 WebSocket 客户端
$ws = new WebSocket($conn);
// 收到消息时的处理
$ws->on('message', function (MessageInterface $msg) use ($ws) {
echo "📥 收到消息: {$msg}\n";
});
// 连接关闭时的处理
$ws->on('close', function ($code = null, $reason = null) {
echo "❌ 连接已关闭: {$code} - {$reason}\n";
});
// 发送 ping 消息测试
echo "📤 发送 ping 消息\n";
$ws->send(json_encode(['action' => 'ping']));
// 发送测试消息
echo "📤 发送测试消息\n";
$ws->send(json_encode(['message' => 'Hello WebSocket!', 'action' => 'test']));
// 3秒后关闭连接
$loop->addTimer(3, function () use ($ws) {
echo "⏰ 关闭连接\n";
$ws->close();
});
// 如果是 aikefu 插件路径,可以发送聊天消息测试
// $ws->send(json_encode(['message' => '你好,客服', 'token' => 'your_token', 'action' => 'chat']));
}, function ($e) use ($loop) {
echo "❌ 连接失败: {$e->getMessage()}\n";
$loop->stop();
});
// 运行事件循环
$loop->run();
echo "测试完成\n";