用AI赚第一桶💰低成本搭建一套AI赚钱工具,源码可二开。 广告
## Swoole Swoole 本身提供了 [协程版本的 Client](https://wiki.swoole.com/wiki/page/p-coroutine_client.html),可进行 TCP 收发,与 PHP Socket 不同的是,Swoole Socket 支持设置协议,这样就不需要手动解析协议了,因为高度封装,所以 mix 就不封装了,用户可直接在 mix 中使用,下面是一个原生 DEMO。 - 将下面代码保存为 `client.php`: > - 在 mix 使用时 `\Swoole\Coroutine\run` 用 `xgo` 代替 > - 其中 EOF 要与 TCP 服务器的 [StartCommand:class](https://github.com/mix-php/mix-skeleton/blob/master/app/Tcp/Commands/StartCommand.php#L40) 中一至 ~~~ <?php const EOF = "\n"; \Swoole\Coroutine\run(function () { $client = new \Swoole\Coroutine\Client(SWOOLE_SOCK_TCP); $client->set([ 'open_eof_check' => true, 'package_eof' => EOF, ]); if (!$client->connect('127.0.0.1', 9503)) { throw new \Swoole\Exception($client->errMsg, $client->errCode); } $client->send('{"method":"foo.bar","params":[],"id":123}' . EOF); while (true) { $data = $client->recv(); if (!$data) { echo "disconnect, [{$client->errCode}] {$client->errMsg}" . PHP_EOL; break; } var_dump(json_decode($data, true)); } }); ~~~ **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) } ~~~