|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +use Workbunny\MysqlProtocol\Packets\HandshakeInitialization; |
| 6 | +use Workbunny\MysqlProtocol\Packets\HandshakeResponse; |
| 7 | +use Workbunny\MysqlProtocol\Utils\Binary; |
| 8 | +use Workbunny\MysqlProtocol\Utils\Packet; |
| 9 | +use Workbunny\MysqlProtocol\Packets\Error; |
| 10 | +use Workbunny\MysqlProtocol\Packets\Command; |
| 11 | +use Workbunny\MysqlProtocol\Packets\Ok; |
| 12 | +use Workerman\Connection\TcpConnection; |
| 13 | + |
| 14 | +require_once __DIR__ . '/../vendor/autoload.php'; |
| 15 | + |
| 16 | +$server = new \Workerman\Worker(); |
| 17 | +$server->name = 'workbunny-mysql-client'; |
| 18 | +$server->onWorkerStart = function () { |
| 19 | + global $clientMysqlHandshakeStatus; |
| 20 | + $clientMysqlHandshakeStatus = $clientMysqlHandshakeStatus ?: 0; |
| 21 | + $client = new \Workerman\Connection\AsyncTcpConnection("MySQL://host.docker.internal:3306"); |
| 22 | + |
| 23 | + $client->onConnect = function (TcpConnection $connection) use (&$clientMysqlHandshakeStatus) { |
| 24 | + $connection->errorHandler = function (Throwable $exception) { |
| 25 | + dump($exception); |
| 26 | + }; |
| 27 | + // 模拟心跳 |
| 28 | + \Workerman\Timer::add(30, function () use ($connection, &$clientMysqlHandshakeStatus) { |
| 29 | + if ($clientMysqlHandshakeStatus > 1) { |
| 30 | + $connection->send(Command::pack([ |
| 31 | + 'command' => Command::COM_QUERY, |
| 32 | + 'data' => 'SELECT 1' |
| 33 | + ])); |
| 34 | + } |
| 35 | + }); |
| 36 | + }; |
| 37 | + |
| 38 | + $client->onMessage = function (TcpConnection $connection, Binary $binary) use (&$clientMysqlHandshakeStatus) { |
| 39 | + dump($binary->dump()); |
| 40 | + // 还未握手 |
| 41 | + if ($clientMysqlHandshakeStatus < 1) { |
| 42 | + // 解析握手包 |
| 43 | + $handshakeInitialization = HandshakeInitialization::unpack($binary); |
| 44 | + $clientMysqlHandshakeStatus = 1; |
| 45 | + $connection->send(HandshakeResponse::pack([ |
| 46 | + 'packet_id' => $handshakeInitialization['packet_id'] + 1, |
| 47 | + "capability_flags" => $handshakeInitialization['capability_flags'], |
| 48 | + "max_packet_size" => 1073741824, |
| 49 | + "character_set" => 33, |
| 50 | + "username" => "root", |
| 51 | + "database" => null, |
| 52 | + "auth_plugin" => $handshakeInitialization['auth_plugin_name'], |
| 53 | + "auth_response" => "", |
| 54 | + ])); |
| 55 | + } |
| 56 | + // 握手还未确认 |
| 57 | + elseif ($clientMysqlHandshakeStatus < 2) { |
| 58 | + if (!$class = Packet::getPacketClass($binary)) { |
| 59 | + echo "Error!\n"; |
| 60 | + return; |
| 61 | + } |
| 62 | + $result = $class::unpack($binary); |
| 63 | + dump($result); |
| 64 | + // todo判定是否握手成功 |
| 65 | + |
| 66 | + } |
| 67 | + // 握手成功 |
| 68 | + else { |
| 69 | + |
| 70 | + dump($binary->dump()); |
| 71 | + } |
| 72 | + }; |
| 73 | + |
| 74 | + $client->connect(); |
| 75 | +}; |
| 76 | + |
| 77 | +\Workerman\Worker::runAll(); |
0 commit comments