当前位置: 首页 > news >正文

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

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

图1

小程序调用SSE接口

const requestTask = wx.request({url: `xxx`, // 需要请求的接口地址enableChunked: true, // enableChunked必须为truemethod: "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.0const requestTask = wx.request({enableChunked: true, // 开启分片模式url: 'xxx', // 需要请求的接口地址enableChunked: true, // enableChunked必须为truemethod: "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);},
http://www.lryc.cn/news/334708.html

相关文章:

  • 深入了解iOS内存(WWDC 2018)笔记-内存诊断
  • 《C语言深度解剖》(4):深入理解一维数组和二维数组
  • 信号处理基础
  • 原地移除数组中所有的元素val,要求时间复杂度为O(N),空间复杂度为O(1)
  • 如何提升产品用户体验?4个工具+6张案例,让你快速吃透!
  • C++学习笔记九--模版
  • 19、差分矩阵
  • wordpress外贸独立站模板
  • HTTP/1.0、HTTP/1.1、HTTP/2.0、HTTP3.0的区别
  • 聚合DNS管理系统v1.0全新发布 域名解析管理系统
  • LabVIEW厂房漏水检测监控系统
  • (3)(3.1) 英特尔Realsense深度摄像头(二)
  • go interface{} 作为函数参数
  • Django之REST Client插件
  • java实现UDP数据交互
  • 护眼台灯怎么选看哪些指标?不踩雷护眼台灯十大排名
  • Web API(六)之正则表达式
  • 304. 前缀和技巧中的边界值处理
  • ios swift5 “Sign in with Apple“(使用苹果登录)怎样接入(第三方登录)集成AppleID登录
  • 时间系列预测总结
  • NineData创始人CEO叶正盛受邀参加『数据技术嘉年华』的技术大会
  • nginx访问路径映射资源目录
  • 数据挖掘|序列模式挖掘及其算法的python实现
  • 3. Django 初探路由
  • 论文笔记:Large Language Models as Analogical Reasoners
  • 第3章 数据定义语言DDL
  • C#操作MySQL从入门到精通(7)——对查询数据进行简单过滤
  • 【CVE复现计划】CVE-2024-0195
  • k8s的ca以及相关证书签发流程
  • 思迈特软件与上海德拓签署战略合作协议,携手赋能企业数字化转型