微信小程序-接入sse数据流并实现打字机效果( ChatGPT )

从流中获取的数据格式如下

图1

小程序调用SSE接口

const requestTask = wx.request({
      url: `xxx`, // 需要请求的接口地址
      enableChunked: true, // enableChunked必须为true
      method: "GET",
      timeout: '120000',
      success(res) {
        console.log(res.data)
      },
      fail: function (error) {
        // 请求失败的操作
        console.error(error);
      },
      complete: function () {
        // 请求完成的操作,无论成功或失败都会执行
        console.log('请求完成', str);
      }
    })
    // 监听服务端返回的数据
    requestTask.onChunkReceived(res => {
      console.log( res, res.data);
    })

我这边接收到的数据类型为Uint8Array,需要处理成text文本(如上图)

在这里插入图片描述

 // 监听服务端返回的数据
    requestTask.onChunkReceived(res => {
      console.log( res, res.data);
      // Uint8Array转为text格式
      let arrayBuffer = res.data;
      let decoder = new TextDecoder('utf-8');
      let text = decoder.decode(arrayBuffer);
      //正则匹配上所有event:data后面的文字
      const eventRegex = /event:data\ndata:"data:(.*?)"/g;
      const eventRegexErr = /event:600\ndata:"(.*?)"/g;
      let matches = [];
      let match;
      if (text.indexOf('600') != -1) {//如果获取响应失败
        while ((match = eventRegexErr.exec(text)) !== null) {
          wx.showToast({
            title: match[1],
          })
          matches.push(match[1]);
        }
        str = str + matches.join('')
      } else {//如果获取响应成功
        while ((match = eventRegex.exec(text)) !== null) {
          matches.push(match[1]);
        }
        //处理成字符串
        str = str + matches.join('')
        console.log(text, str);
      }
    })

使对话有打字机效果

参考自:小程序实现 ChatGPT 聊天打字兼自动滚动效果

 handleRequestResolve(result) {
    this.setData({
      currentContent: ''
    })
    const contentCharArr = result.trim().split("")
    this.showText(0, contentCharArr);
  },
  showText(key = 0, value) {
    /* 所有内容展示完成 */
    if (key >= value.length) {
      // wx.vibrateShort()
      return;
    }
    /* 渲染回话内容 */
    this.setData({
      currentContent: this.data.currentContent + value[key],
    })
    setTimeout(() => {
      /* 递归渲染内容 */
      this.showText(key + 1, value);
    }, 50);
  },

完整代码

 getDataStream(data) {
    let str = ''
    let that = this
    // 基础库为2.33.0
    const requestTask = wx.request({
      enableChunked: true, // 开启分片模式
      url: 'xxx', // 需要请求的接口地址
      enableChunked: true, // enableChunked必须为true
      method: "GET",
      responseType: "arraybuffer",
      timeout: '120000',
      success(res) {
        console.log(res.data)
      },
      fail: function (error) {
        // 请求失败的操作
        console.error(error);
      },
      complete: function () {
        // 请求完成的操作,无论成功或失败都会执行
        console.log('请求完成', str);
      }
    })
    // 监听服务端返回的数据
    requestTask.onChunkReceived(res => {
      console.log(res, res.data);
      // Uint8Array转为text格式
      let arrayBuffer = res.data;
      let decoder = new TextDecoder('utf-8');
      let text = decoder.decode(arrayBuffer);
      //正则匹配上所有event:data后面的文字
      const eventRegex = /event:data\ndata:"data:(.*?)"/g;
      const eventRegexErr = /event:600\ndata:"(.*?)"/g;
      let matches = [];
      let match;
      if (text.indexOf('600') != -1) { //如果获取响应失败
        while ((match = eventRegexErr.exec(text)) !== null) {
          wx.showToast({
            title: match[1],
          })
          matches.push(match[1]);
        }
        str = str + matches.join('')
      } else { //如果获取响应成功
        while ((match = eventRegex.exec(text)) !== null) {
          matches.push(match[1]);
        }
        //处理成字符串
        str = str + matches.join('')
        console.log(text, str);
      }
      that.handleRequestResolve(str)

    })
    requestTask.offChunkReceived(res => {
      console.log('事件完成状态');
    })
  },
 handleRequestResolve(result) {
    this.setData({
      currentContent: ''
    })
    const contentCharArr = result.trim().split("")
    this.showText(0, contentCharArr);
  },
  showText(key = 0, value) {
    /* 所有内容展示完成 */
    if (key >= value.length) {
      // wx.vibrateShort()
      return;
    }
    /* 渲染回话内容 */
    this.setData({
      currentContent: this.data.currentContent + value[key],
    })
    setTimeout(() => {
      /* 递归渲染内容 */
      this.showText(key + 1, value);
    }, 50);
  },

相关推荐

  1. 程序】canvas绘实现贴纸效果

    2024-04-09 06:36:01       52 阅读
  2. 程序实现下拉简单展示接口数据

    2024-04-09 06:36:01       58 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-09 06:36:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-09 06:36:01       101 阅读
  3. 在Django里面运行非项目文件

    2024-04-09 06:36:01       82 阅读
  4. Python语言-面向对象

    2024-04-09 06:36:01       91 阅读

热门阅读

  1. springboot设置RestTemplate支持http&https

    2024-04-09 06:36:01       32 阅读
  2. Qt-线程2-moveToThread

    2024-04-09 06:36:01       37 阅读
  3. Rust---解构(Destructuring)

    2024-04-09 06:36:01       32 阅读
  4. Junit

    Junit

    2024-04-09 06:36:01      29 阅读
  5. 中国移动运营商网络码大全-2024

    2024-04-09 06:36:01       63 阅读
  6. arm-none-eabi-addr2line和arm-none-eabi-objdump使用笔记

    2024-04-09 06:36:01       29 阅读