马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
以下是一个完备的 JavaScript 数据流式获取实现方案,模仿雷同 DeepSeek 的对话式逐段返回效果。包罗前端实现、后端模仿和详细解释:
后端 Node.js 实现(Express):- const express = require('express');
- const app = express();
- const port = 3000;
- // 允许跨域
- app.use((req, res, next) => {
- res.header('Access-Control-Allow-Origin', '*');
- next();
- });
- // 流式端点
- app.get('/stream', (req, res) => {
- // 设置流式响应头
- res.writeHead(200, {
- 'Content-Type': 'text/event-stream',
- 'Cache-Control': 'no-cache',
- 'Connection': 'keep-alive'
- });
- // 模拟的对话数据
- const responseText = [
- "你好!我是 DeepSeek 的智能助手。",
- "我正在分析您的问题...",
- "根据现有数据,建议如下:\n",
- "1. 首先检查网络连接\n",
- "2. 验证 API 密钥有效性\n",
- "3. 查看服务状态面板\n",
- "\n需要更详细的帮助吗?"
- ];
- // 发送流式数据
- let index = 0;
- const sendChunk = () => {
- if (index < responseText.length) {
- const chunk = {
- content: responseText[index],
- finished: index === responseText.length - 1
- };
-
- // SSE 格式要求
- res.write(`data: ${JSON.stringify(chunk)}\n\n`);
-
- index++;
- setTimeout(sendChunk, 500); // 控制发送速度
- } else {
- res.end();
- }
- };
- sendChunk();
- // 处理客户端断开连接
- req.on('close', () => {
- console.log('客户端断开连接');
- res.end();
- });
- });
- app.listen(port, () => {
- console.log(`服务运行在 http://localhost:${port}`);
- });
复制代码 焦点实现原理:
- 利用 Fetch API + ReadableStream 处理处罚流式数据
- 支持哀求停止(AbortController)
- 实现打字机动画效果
- 自动滚动保持内容可见
- 加载状态指示
- 利用 Server-Sent Events (SSE) 协议
- 分块发送 JSON 格式数据
- 模仿真实相应延长(500ms/块)
- 支持客户端断开检测
- {
- "content": "当前内容片段",
- "finished": false
- }
复制代码 优化扩展发起:
- // 添加节流控制
- const throttle = (func, limit) => {
- let lastFunc;
- let lastRan;
- return function(...args) {
- if (!lastRan) {
- func.apply(this, args);
- lastRan = Date.now();
- } else {
- clearTimeout(lastFunc);
- lastFunc = setTimeout(() => {
- if ((Date.now() - lastRan) >= limit) {
- func.apply(this, args);
- lastRan = Date.now();
- }
- }, limit - (Date.now() - lastRan));
- }
- };
- };
- // 在 appendContent 中使用
- this.appendContent = throttle(this.appendContent, 50);
复制代码- // 前端添加错误处理
- async start() {
- try {
- // ...原有逻辑...
- } catch (error) {
- if (error.name === 'AbortError') {
- this.appendContent('\n[对话已中止]');
- } else {
- this.appendContent(`\n[错误: ${error.message}]`);
- console.error('Stream Error:', error);
- }
- }
- }
- // 后端添加错误模拟
- app.get('/stream', (req, res) => {
- // 10% 概率模拟错误
- if (Math.random() < 0.1) {
- res.writeHead(500);
- res.end();
- return;
- }
- // ...原有逻辑...
- });
复制代码- // 添加 Markdown 支持
- appendContent(text) {
- // 简单 Markdown 解析
- const parsed = text
- .replace(/#{3}/g, '<h3>')
- .replace(/#{2}/g, '<h2>')
- .replace(/#{1}/g, '<h1>')
- .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
-
- // 使用 DocumentFragment 优化渲染
- const fragment = document.createDocumentFragment();
- const span = document.createElement('span');
- span.innerHTML = parsed;
- fragment.appendChild(span);
-
- this.output.appendChild(fragment);
- }
复制代码 这个实现方案完备展示了:
- 前后端流式通讯的全流程
- 实时内容渲染优化本领
- 完备的错误处理处罚机制
- 可扩展的架构筹划
- 用户体验优化细节
实际摆设时,发起:
- 利用 WebSocket 更换 SSE 实现双向通讯
- 添加 JWT 鉴权
- 实现速率限定(Rate Limiting)
- 摆设到支持 HTTP/2 的服务器
- 添加前端缓存战略
|