|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +use Workbunny\MysqlProtocol\Packets\HandshakeInitialization; |
| 6 | +use Workbunny\MysqlProtocol\Utils\Binary; |
| 7 | +use Workbunny\MysqlProtocol\Utils\Packet; |
| 8 | +use Workbunny\MysqlProtocol\Packets\Error; |
| 9 | +use Workbunny\MysqlProtocol\Packets\Command; |
| 10 | +use Workbunny\MysqlProtocol\Packets\Ok; |
| 11 | +use Workerman\Connection\TcpConnection; |
| 12 | + |
| 13 | +require_once __DIR__ . '/vendor/autoload.php'; |
| 14 | + |
| 15 | +$server = new \Workerman\Worker("MySQL://0.0.0.0:8844"); |
| 16 | +$server->name = 'workbunny-mysql-server'; |
| 17 | +$server->count = 2; |
| 18 | +$server->onConnect = function (TcpConnection $connection) { |
| 19 | + // 构造握手包所需数据(这些数据可根据实际服务器配置、能力及认证数据来定制) |
| 20 | + $handshakeData = [ |
| 21 | + // 通常,协议版本固定为 10 |
| 22 | + 'protocol_version' => 10, |
| 23 | + // 服务器版本 |
| 24 | + 'server_version' => '8.4.3-workbunny', |
| 25 | + // 连接 ID(示例值,可以自定义) |
| 26 | + 'connection_id' => $connection->id, |
| 27 | + // 能力标识 |
| 28 | + 'capability_flags' => 3758096383, |
| 29 | + // 字符集索引 |
| 30 | + 'character_set_index'=> 255, |
| 31 | + // 状态标识 |
| 32 | + 'status_flags' => 2, |
| 33 | + // 认证数据,必须至少 8 字节(示例数据) |
| 34 | + 'auth_plugin_data' => Packet::authData(21), |
| 35 | + // 认证插件名称(MySQL 8 默认认证插件通常是 caching_sha2_password) |
| 36 | + 'auth_plugin_name' => 'caching_sha2_password' |
| 37 | + ]; |
| 38 | + // 生成握手包的 Binary 对象 |
| 39 | + $binary = HandshakeInitialization::pack($handshakeData); |
| 40 | + // 握手状态机 |
| 41 | + $connection->mysql_handshake_status = 0; |
| 42 | + $connection->send($binary); |
| 43 | +}; |
| 44 | + |
| 45 | +$server->onMessage = function (TcpConnection $connection, Binary $binary) { |
| 46 | + // 友好打印 |
| 47 | + dump($binary->dump()); |
| 48 | + // 判断状态机 |
| 49 | + if (!isset($connection->mysql_handshake_status)) { |
| 50 | + $connection->close(Error::pack([ |
| 51 | + 'error_code' => 0, |
| 52 | + 'sql_state' => 'HY000', |
| 53 | + 'message' => 'Invalid connection.', |
| 54 | + ])); |
| 55 | + return; |
| 56 | + } |
| 57 | + // 状态机:0 握手阶段,1 已经握手 |
| 58 | + if ($connection->mysql_handshake_status < 1) { |
| 59 | + // todo 可以对 数据信息进行验证,这里暂时不验证用户信息等 |
| 60 | +// \Workbunny\MysqlProtocol\Packets\HandshakeResponse::unpack($binary); |
| 61 | + |
| 62 | + // 状态机:1 已经握手 |
| 63 | + $connection->mysql_handshake_status = 1; |
| 64 | + $connection->send(Ok::pack([])); |
| 65 | + } else { // command包 |
| 66 | + $command = Command::unpack($binary); |
| 67 | + dump($command); |
| 68 | + $connection->send(Ok::pack([ |
| 69 | + 'packet_id' => $command['packet_id'] ?? 0, |
| 70 | + ])); |
| 71 | + } |
| 72 | +}; |
0 commit comments