## Swoole Swoole 本身提供了 [协程版本的客户端](https://wiki.swoole.com/wiki/page/868.html),因为高度封装,所以 mix 就不封装了,用户可直接在 mix 中使用,下面是一个原生 DEMO。 - 将下面代码保存为 `client.php`: > 在 mix 使用时 `\Swoole\Coroutine\run` 用 `xgo` 代替 ~~~ <?php \Swoole\Coroutine\run(function () { $cli = new \Swoole\Coroutine\http\Client('127.0.0.1', 9502); $ret = $cli->upgrade("/websocket"); if ($ret) { $frame = new Swoole\WebSocket\Frame(); $frame->opcode = SWOOLE_WEBSOCKET_OPCODE_TEXT; $frame->data = '{"method":"join.room","params":[1012,"小明"],"id":1}'; $cli->push($frame); $frame = new Swoole\WebSocket\Frame(); $frame->opcode = SWOOLE_WEBSOCKET_OPCODE_TEXT; $frame->data = '{"method":"message.emit","params":["大家好"],"id":2}'; $cli->push($frame); while (true) { $data = $cli->recv(); if (!$data || $data instanceof \Swoole\WebSocket\CloseFrame) { echo "disconnect" . PHP_EOL; break; } var_dump($data); } } }); ~~~ **1. 启动 mix-websocketd 服务** ~~~ php bin/mix.php ws:start --host=0.0.0.0 --port=9502 ~~~ **2. 执行 `client.php`** ~~~ php client.php ~~~ 接收到加入成功的消息: ~~~ [root@localhost /]# php client.php object(Swoole\WebSocket\Frame)#4 (4) { ["fd"]=> int(0) ["data"]=> string(67) "{"jsonrpc":"2.0","error":null,"result":{"status":"success"},"id":1}" ["opcode"]=> int(1) ["finish"]=> bool(true) } object(Swoole\WebSocket\Frame)#5 (4) { ["fd"]=> int(0) ["data"]=> string(67) "{"jsonrpc":"2.0","error":null,"result":{"status":"success"},"id":2}" ["opcode"]=> int(1) ["finish"]=> bool(true) } object(Swoole\WebSocket\Frame)#4 (4) { ["fd"]=> int(0) ["data"]=> string(90) "{"jsonrpc":"2.0","method":"message.update","params":["大家好",1012,"小明"],"id":null}" ["opcode"]=> int(1) ["finish"]=> bool(true) } ~~~