在webman控制器中使用http-client由于無法將請(qǐng)求第三方接口的響應(yīng),響應(yīng)給前端,所以我參考了http://www.wtbis.cn/q/9562
我的下面的代碼是一個(gè)請(qǐng)求tts的接口,然后將音頻數(shù)據(jù)返回給前端,我現(xiàn)在有一個(gè)問題就是自定義進(jìn)程中的異步請(qǐng)求是如何實(shí)現(xiàn)給前端響應(yīng)的呢?我總是有一種同步的錯(cuò)覺,還有就是,如果請(qǐng)求耗時(shí),是否會(huì)影響下一次請(qǐng)求呢?
<?php
namespace app;
use support\Response;
use Workerman\Connection\TcpConnection;
use Workerman\Http\Client;
use Workerman\Protocols\Http\Request;
class Api
{
public function onMessage(TcpConnection $connection, Request $request)
{
$text=$request->post("text");
//if ($request->path() == '/test/test') {
$options = [
'max_conn_per_addr' => 128, // 每個(gè)地址最多維持多少并發(fā)連接
'keepalive_timeout' => 15, // 連接多長時(shí)間不通訊就關(guān)閉
'connect_timeout' => 30, // 連接超時(shí)時(shí)間
'timeout' => 30, // 等待響應(yīng)的超時(shí)時(shí)間
];
$http = new Client($options);
$http->request('/v1/audio/speech', [
'method' => 'POST',
'version' => '1.1',
'headers' => ['Connection' => 'keep-alive'],
'data' => json_encode(["input"=>$text,"model"=>"tts-1","voice"=>"zh-CN-XiaoxiaoNeural"]),
'success' => function ($response)use($connection,$request) {
$res=new Response(200,[
'Content-Type' => 'audio/mpeg',
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Allow-Origin' => $request->header('origin', '*'),
'Access-Control-Allow-Methods' => $request->header('access-control-request-method', '*'),
'Access-Control-Allow-Headers' => $request->header('access-control-request-headers', '*'),
],$response->getBody());
$connection->send($res);
},
'error' => function ($exception) {
echo $exception;
}
]);
return;
// }
// $connection->send(response('404 not found'), 404);
}
}