workerman websocket協(xié)議 send 怎么流式發(fā)送數(shù)據(jù),為什么都是一起返回的;
windows 本地測(cè)試正常,可以流式輸出, linux 服務(wù)器上不行, 都是一起輸出的。
<?php
use Workerman\Connection\TcpConnection;
use Workerman\Worker;
use Workerman\Lib\Timer;
use Workerman\Protocols\Http\Request;
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker('websocket://0.0.0.0:5556');
//$worker = new Worker('websocket://0.0.0.0:5556', ['ssl' => ['local_cert' => __DIR__."/dm299.pem", 'local_pk' => __DIR__."/dm299.key", 'verify_peer' => false]]);
//$worker->transport = 'ssl';
$worker->onMessage = function(TcpConnection $connection, $data) {
$url = 'https://demo.xxxxxxxxxxxx.com/ai.php';
$postData = []; // 假設(shè)這是你要發(fā)送的數(shù)據(jù)
$headers = []; // 假設(shè)這是你的請(qǐng)求頭
// 定義回調(diào)函數(shù),并通過(guò) use 關(guān)鍵字傳遞 $connection
$writeCallback = function($ch, $data) use ($connection) {
// 處理接收到的數(shù)據(jù)塊
$length = strlen($data); // 獲取數(shù)據(jù)塊的長(zhǎng)度
$connection->send($data."<br>",true); // 將數(shù)據(jù)發(fā)送給客戶端
return $length; // 返回處理的數(shù)據(jù)長(zhǎng)度
};
// 發(fā)起 cURL 請(qǐng)求
$response = curlPost($url, json_encode($postData), $headers, $writeCallback);
// 檢查是否有錯(cuò)誤
if (isset($response['error'])) {
$connection->send("請(qǐng)求失敗: " . $response['error']['message']);
} else {
$connection->send("傳輸完成");
}
};
function curlPost($url, $params, $headers = [], $writeCallback = null) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// 如果提供了回調(diào)函數(shù),則設(shè)置 CURLOPT_WRITEFUNCTION
if ($writeCallback) {
curl_setopt($ch, CURLOPT_WRITEFUNCTION, $writeCallback);
}
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120); // 連接超時(shí)時(shí)間
curl_setopt($ch, CURLOPT_TIMEOUT, 120); // 請(qǐng)求超時(shí)時(shí)間
$response = curl_exec($ch);
if (curl_errno($ch)) {
return ['error' => ['message' => curl_error($ch)]];
}
curl_close($ch);
return $response;
}
Worker::runAll();
?>