🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
异步 TCP 客户端与上一个同步 TCP 客户端不同,异步客户端是非阻塞的。更适合编写高并发的程序。需要注意的一点是 异步 TCP 客户端只能运行在命令行环境下。 接下来我们演示一下如何用 ThinkPHP5 和 Swoole 来构架一个异步 TCP 客户端 创建 ThinkPHP5 自定义命令行 1.创建命令行类 - 创建application/console/AsyncTcpClient.php文件 ~~~ <?php namespace app\Console; use think\console\Command; use think\console\Input; use think\console\Output; class AsyncTcpClient extends Command { protected $client; // 命令行配置函数 protected function configure() { // setName 设置命令行名称 // setDescription 设置命令行描述 $this->setName('async_tcp:client')->setDescription('Start Async TCP Client!'); } // 设置命令返回信息 protected function execute(Input $input, Output $output) { // 实例化客户端 $this->client = new \swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC); // 注册回调函数 $this->client->on('Connect', [$this, 'onConnect']); $this->client->on('Receive', [$this, 'onReceive']); $this->client->on('Error', [$this, 'onError']); $this->client->on('Close', [$this, 'onClose']); //发起连接 $this->client->connect('127.0.0.1', 9501, 0.5); } // 注册连接成功回调 public function onConnect(\swoole_client $cli) { $cli->send("hello world\n"); } // 注册数据接收回调 public function onReceive(\swoole_client $cli, $data) { echo "message sending\n"; echo "Received: ".$data."\n"; } // 注册连接失败回调 public function onError(\swoole_client $cli) { echo "Connect failed\n"; } // 注册连接关闭回调 public function onClose(\swoole_client $cli) { echo "Connection close\n"; } } ~~~ 2.修改配置文件 - 文件所在 application/command.php ~~~ <?php return [ 'app\console\AsyncTcpClient', ]; ~~~ 接下来就可以通过命令行来启动 TCP 客户端 $ > `php think async_tcp:client` 启动后会自动向 TCP 服务器发送数据,收到数据后会自动显示出来。 ![](https://box.kancloud.cn/078d0e9cb4c5ee5966655966face672b_546x68.png)