请问,webman能向浏览器发送流数据(多次发送数据)吗

深林孤鹰

问题描述

最近在研究openai的接口,它有一个steam功能,就是在curl时设置 CURLOPT_WRITEFUNCTION 属性,可以不停的回调这个函数并输出流到浏览器,官方示例差不多是这样子:
$open_ai->completion($opts, function ($curl_info, $data) {
echo $data . "<br>"; //不停输出数据
ob_flush();
flush();
return strlen($data);
});
用php原生,浏览器会不停的输出数据,但webman的echo是输出到控制台的,所以请问如何在这个回调函数里向浏览器实时发送数据流呢?
谢谢各路大神驻留帮助~

2023 1 10
1个回答

walkor 打赏

webman SSE方案

参考 https://www.workerman.net/q/10107

以下是 webman Http Chunk 方案

创建 process/HttpChunk.php

<?php
namespace process;

use Workerman\Connection\TcpConnection;
use Workerman\Protocols\Http\Request;
use Workerman\Protocols\Http\Chunk;
use Workerman\Protocols\Http\Response;
use Workerman\Timer;

class HttpChunk
{
    public function onMessage(TcpConnection $connection, Request $request)
    {
        // 首先发送一个带Transfer-Encoding: chunked头的Response响应
        $total_count = 10;
        $connection->send(new Response(200, array('Transfer-Encoding' => 'chunked'), "共{$total_count}段数据<br>"));
        $timer_id = Timer::add(2, function () use ($connection, &$timer_id, $total_count){
            static $count = 0;
            // 连接关闭的时候要将定时器删除,避免定时器不断累积导致内存泄漏
            if ($connection->getStatus() !== TcpConnection::STATUS_ESTABLISHED) {
                Timer::del($timer_id);
                return;
            }
            if ($count++ >= $total_count) {
                // 发送一个空的''代表结束响应
                $connection->send(new Chunk(''));
                return;
            }
            // 发送chunk数据
            $connection->send(new Chunk("第{$count}段数据<br>"));
        });
    }
}

config/process.php 怎加配置

<?php
return [
    // ... 其它配置 ...

    'http-chunk' => [
        'listen' => 'http://0.0.0.0:8585',
        'handler' => \process\HttpChunk::class,
    ]
];

浏览器访问 http://127.0.0.1:8585 页面会定时输出数据

相关文档

https://www.workerman.net/doc/workerman/http/response.html#%E5%8F%91%E9%80%81http%20chunk%E6%95%B0%E6%8D%AE
https://www.workerman.net/doc/workerman/http/SSE.html

年代过于久远,无法发表回答
×
🔝