## PHP TCP 服务是基于 Socket 开发的,因此客户端我们能直接使用 PHP 的 Socket 操作方法连接,得益于 [Swoole 的 Hook](https://wiki.swoole.com/wiki/page/p-runtime.html) 技术 (mix 默认已经开启 Hook) ,PHP 的原生 Socket 操作可在协程中使用。 - 将下面代码保存为 `client.php`: > 其中 EOF 要与 TCP 服务器的 [StartCommand:class](https://github.com/mix-php/mix-skeleton/blob/master/app/Tcp/Commands/StartCommand.php#L40) 中一至 ~~~ <?php /** * Class JsonRpcTcpClient * @author liu,jian <coder.keda@gmail.com> */ class JsonRpcTcpClient { /** * @var resource */ public $socket; /** * @var string */ public $eof = "\n"; /** * @var int */ public $timeout = 5; /** * @var int */ public $lineMaxLength = 4096; /** * JsonRpcTcpClient constructor. * @param string $host * @param int $port */ public function __construct(string $host, int $port) { $socket = stream_socket_client("tcp://{$host}:{$port}", $errno, $errstr, $this->timeout); if (!$socket) { throw new \RuntimeException("JSON-RPC tcp client connection failed, [$errno] {$errstr}"); } $this->socket = $socket; } /** * 执行方法 * @param string $method * @param array $params * @param int $id * @return array */ public function call(string $method, array $params, int $id = 0) { $ret = fwrite($this->socket, json_encode([ 'method' => $method, 'params' => $params, 'id' => $id, ]) . $this->eof); if ($ret === false) { throw new \RuntimeException('JSON-RPC tcp client write failed.'); } stream_set_timeout($this->socket, $this->timeout); $data = stream_get_line($this->socket, $this->lineMaxLength, $this->eof); if ($data === false) { throw new \RuntimeException('JSON-RPC tcp client read failed.'); } return json_decode($data, true); } /** * Destruct */ public function __destruct() { // TODO: Implement __destruct() method. fclose($this->socket); } } // 执行RPC $client = new JsonRpcTcpClient('127.0.0.1', 9503); $result = $client->call('foo.bar', [], 123); var_dump($result); ~~~ **1. 启动服务器** ~~~ php bin/mix.php tcp:start ~~~ **2. 执行 `client.php`** ~~~ php client.php ~~~ 接收到加入成功的消息: ~~~ [root@localhost data]# php client.php array(4) { ["jsonrpc"]=> string(3) "2.0" ["error"]=> NULL ["result"]=> array(1) { [0]=> string(13) "Hello, World!" } ["id"]=> int(123) } ~~~