This commit is contained in:
mkm 2023-09-13 19:01:47 +08:00
parent a7683eaf40
commit 594afcf7f1

View File

@ -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();
}
}