From 594afcf7f1d7f2f2e64ca76b5a548dd42c15a108 Mon Sep 17 00:00:00 2001 From: mkm <727897186@qq.com> Date: Wed, 13 Sep 2023 19:01:47 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Pusher.php | 53 +++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 42 insertions(+), 11 deletions(-) diff --git a/app/Pusher.php b/app/Pusher.php index 32a6b6d..a49b292 100644 --- a/app/Pusher.php +++ b/app/Pusher.php @@ -6,6 +6,7 @@ use Workerman\Connection\TcpConnection; use IFlytek\Xfyun\Speech\ChatClient; use WebSocket\Client; use Workerman\Connection\AsyncTcpConnection; +use support\Request; class Pusher { @@ -28,19 +29,49 @@ class Pusher public function onMessage(TcpConnection $connection, $data) { if ($data != '') { - $uri = $this->assembleAuthUrl('ws://spark-api.xf-yun.com/v2.1/chat'); - $con = new AsyncTcpConnection($uri); - $con->onWebSocketConnect = function (AsyncTcpConnection $con,$data) { - $res = $this->getBody($this->app_id,$data); - $con->send($res); - }; - // $con->onMessage = function (TcpConnection $connection, $res) { - // // var_dump($res); - // // $con->send($res); - // $connection->send($res); + $client = new Client($this->assembleAuthUrl('wss://spark-api.xf-yun.com/v2.1/chat')); + // 连接到 WebSocket 服务器 + if ($client) { + // 发送数据到 WebSocket 服务器 + $data = $this->getBody($this->app_id, $data); + + $client->send($data); + // 从 WebSocket 服务器接收数据 + while (true) { + $response = $client->receive(); + $resp = json_decode($response, true); + $code = $resp["header"]["code"]; + // echo "从服务器接收到的数据: " . $response; + if(0 == $code){ + $status = $resp["header"]["status"]; + if($status != 2){ + // $content = $resp['payload']['choices']['text'][0]['content']; + $connection->send($response); + }else{ + // $content = $resp['payload']['choices']['text'][0]['content']; + $connection->send($response); + + // $total_tokens = $resp['payload']['usage']['text']['total_tokens']; + print("\n本次消耗token用量:\n"); + + break; + } + } + } + } + // $uri = $this->assembleAuthUrl('ws://spark-api.xf-yun.com/v2.1/chat'); + // $con = new AsyncTcpConnection($uri); + // // $con = new AsyncTcpConnection('ws://127.0.0.1:9999'); + // $con->onWebSocketConnect = function (AsyncTcpConnection $con,$data) { + // $res = $this->getBody($this->app_id,$data); + // $con->send($res); + // }; + // $con->onMessage = function (AsyncTcpConnection $con, $data) use($connection) { + + // $connection->send($data); // }; - $con->connect(); + // $con->connect(); } }