HarmonyOS鸿蒙Next中利用rcp.NetworkInputQueue流式输出问题

HarmonyOS鸿蒙Next中利用rcp.NetworkInputQueue流式输出问题

我的请求代码如下:

async streamRequest(path: string, method: string, requestParam: rcp.RequestContent | undefined,
  option: HttpRequestOption, onMessage: (message: string | null) => void, paceMs: number = 0) {
  // 创建同步读队列对象
  const networkOutputQueue = new rcp.NetworkOutputQueue();
  let dialogId: string | null = null
  let intervalId: number | null = null
  try {
    if (option.showLoading) {
      dialogId = LoadingUtil.showLoadingDialog()
    }
    let resp = await this.streamSession.post(path, requestParam, networkOutputQueue)
    if (resp.statusCode != 200) {
      if (dialogId != null) {
        DialogHelper.closeDialog(dialogId)
      }
     else
        throw new CustomError('响应失败,错误码:' + resp.statusCode, -1)
    }
    let arr = new ArrayBuffer(100)
    let len: number
    while ((len = networkOutputQueue.readInto(arr)) > 0) {
      let decoder = util.TextDecoder.create('utf-8');
      let respStr = decoder.decodeToString(new Uint8Array(arr.slice(0, len)));
      console.error('stream-resp', respStr)
      onMessage(respStr.replace(/\s+/g, ''))
    }
  } catch (e) {
    if (dialogId != null) {
      DialogHelper.closeDialog(dialogId)
    }
    if (option.showErrorToast) {
      if (e instanceof CustomError) {
        ToastUtil.showToast(e.message)
      } else {
        console.error('Http-Error', (e as Error).message + (e as Error).name)
        ToastUtil.showToast("网络请求失败,请检查网络连接或重试")
      }
    }
    if (intervalId) {
      clearInterval(intervalId)
    }
    throw e as Error
  }
}
每次我拿到的respStr都是截断的,成功响应一次后,流就关闭了,而不是得到循环获得流式的响应
我参考的文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/remote-communication-syncstreamreq

更多关于HarmonyOS鸿蒙Next中利用rcp.NetworkInputQueue流式输出问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html

3 回复

已解决

更多关于HarmonyOS鸿蒙Next中利用rcp.NetworkInputQueue流式输出问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


HarmonyOS Next中,rcp.NetworkInputQueue用于处理网络输入流。流式输出问题通常涉及数据读取与处理。可通过监听队列事件,使用回调函数异步获取数据。确保正确配置网络权限与队列参数,避免阻塞主线程。数据解析需匹配协议格式,错误处理应涵盖网络异常与数据校验。

从你的代码来看,问题可能出在 while 循环读取数据的方式上。在 HarmonyOS Next 中,NetworkOutputQueue.readInto() 方法在流式响应中,当服务器持续发送数据时,它可能不会一次性返回所有数据,但你的代码逻辑假设一次 post 请求后,可以通过循环读取到全部流式数据,这通常不是标准流式响应的处理方式。

标准的流式处理应该是基于事件或回调的。根据你提供的文档链接,rcp.NetworkOutputQueue 通常与 rcp.NetworkInputQueue 配对使用,用于双向流式通信。你的代码只使用了 NetworkOutputQueue 来读取响应,但可能没有正确配置会话(streamSession)以支持持续的流式响应。

建议检查以下几点:

  1. 确保服务器端确实支持并正确设置了流式响应(如 Transfer-Encoding: chunked)。
  2. 检查 streamSession.post 方法是否支持流式请求,可能需要设置特定的选项来保持连接开放。
  3. 考虑使用 rcp 模块中其他专为流式设计的方法,例如监听数据到达的事件,而不是依赖循环读取。

由于代码片段不完整,特别是 streamSession 的配置和服务器响应细节未知,这可能是导致流提前关闭的原因。

回到顶部