嘉兴网站设计,wordpress 引用视频,响应式网站模板怎么做,仿做网站可以整站下载器吧本篇博客将带领你使用 Spring Boot、WebSocket 和 JavaScript 实现一个类似 ChatGPT 的流式回复效果。前端发送消息后#xff0c;后端接收消息并请求 AI API#xff0c;并将 AI 返回的流式响应实时推送到前端#xff0c;最终在聊天界面呈现出逐字出现的打字效果。
技术原理…本篇博客将带领你使用 Spring Boot、WebSocket 和 JavaScript 实现一个类似 ChatGPT 的流式回复效果。前端发送消息后后端接收消息并请求 AI API并将 AI 返回的流式响应实时推送到前端最终在聊天界面呈现出逐字出现的打字效果。
技术原理 WebSocket 全双工通信: WebSocket 协议提供全双工通信通道允许服务器和客户端之间进行双向实时数据传输非常适合实现流式数据传输。 Spring WebFlux 响应式编程: Spring WebFlux 基于 Reactor 库支持响应式流处理可以处理 AI API 返回的流式数据。 SSEServer-Sent Events SSE 是一种基于 HTTP 的单向服务器推送技术可以将 AI 返回的流式数据实时推送到前端。
实现步骤
一、后端实现 (Spring Boot)
添加依赖
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-websocket/artifactId
/dependency
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-webflux/artifactId
/dependency创建 WebSocket 处理器
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;import java.time.Duration;Controller
public class ChatController {Autowiredprivate SimpMessagingTemplate messagingTemplate;Autowiredprivate WebClient webClient; // 用于调用 AI APIMessageMapping(/chat.sendMessage) // 接收来自客户端的消息public void sendMessage(Payload Message message) throws Exception {// 构造 AI API 请求ApiRequest apiRequest new ApiRequest(message.getContent()); // 假设 AI API 接受 ApiRequest 对象// 调用 AI API获取流式响应FluxString apiResponse callAiApi(apiRequest);// 处理 AI API 响应并逐条发送给前端apiResponse.delayElements(Duration.ofMillis(50)) // 模拟打字延迟.subscribe(chunk - {Message responseMessage new Message(AI, chunk);messagingTemplate.convertAndSend(/topic/chat, responseMessage);});}// 调用 AI APIprivate FluxString callAiApi(ApiRequest request) {// 将 ApiRequest 对象转换为 JSON 字符串// ...// 发送 POST 请求并指定返回数据类型为 FluxStringreturn webClient.post().uri(https://api.example.com/ai-api) // 替换为实际的 AI API 地址.bodyValue(request).retrieve().bodyToFlux(String.class);}// 消息类public static class Message {private String sender;private String content;// 构造函数getter 和 setter}// AI API 请求类public static class ApiRequest {private String prompt;// 构造函数getter 和 setter}
}WebSocket 配置
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;Configuration
EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {Overridepublic void configureMessageBroker(MessageBrokerRegistry config) {config.enableSimpleBroker(/topic);config.setApplicationDestinationPrefixes(/app);}Overridepublic void registerStompEndpoints(StompEndpointRegistry registry) {registry.addEndpoint(/ws).withSockJS();}
}二、前端实现 (JavaScript)
!DOCTYPE html
html
headtitleChat Application/titlescript srchttps://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.5.1/sockjs.min.js/scriptscript srchttps://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js/script
/head
bodydiv idchat-containerdiv idchat-output/divinput typetext idmessage-input placeholderEnter message...button onclicksendMessage()Send/button/divscript// 连接 WebSocketvar socket new SockJS(/ws);var stompClient Stomp.over(socket);stompClient.connect({}, function(frame) {console.log(Connected: frame);// 订阅聊天频道stompClient.subscribe(/topic/chat, function(message) {showMessage(JSON.parse(message.body));});});// 发送消息function sendMessage() {var message document.getElementById(message-input).value;stompClient.send(/app/chat.sendMessage, {}, JSON.stringify({sender: user, // 可替换为实际用户名content: message}));}// 显示消息function showMessage(message) {var chatOutput document.getElementById(chat-output);var messageElement document.createElement(div);if (message.sender AI) {// AI 回复逐字显示typeWriter(messageElement, message.content, 0);} else {messageElement.innerHTML strong message.sender :/strong message.content;chatOutput.appendChild(messageElement);}}// 模拟打字效果function typeWriter(element, text, i) {if (i text.length) {element.innerHTML text.charAt(i);setTimeout(function() {typeWriter(element, text, i 1);}, 50); // 调整打字速度} else {document.getElementById(chat-output).appendChild(element);}}/script
/body
/html总结
本文介绍了如何使用 Spring Boot 和 WebSocket 实现类似 ChatGPT 的流式回复效果并详细讲解了每个步骤的技术原理和代码实现。通过这种方式我们可以构建更加 engaging 和 interactive 的 Web 应用为用户带来全新的体验。 文章转载自: http://www.morning.qtqjx.cn.gov.cn.qtqjx.cn http://www.morning.rkrl.cn.gov.cn.rkrl.cn http://www.morning.qnhpq.cn.gov.cn.qnhpq.cn http://www.morning.fpczq.cn.gov.cn.fpczq.cn http://www.morning.zlnf.cn.gov.cn.zlnf.cn http://www.morning.yydzk.cn.gov.cn.yydzk.cn http://www.morning.qftzk.cn.gov.cn.qftzk.cn http://www.morning.gwxsk.cn.gov.cn.gwxsk.cn http://www.morning.lpnpn.cn.gov.cn.lpnpn.cn http://www.morning.fhtbk.cn.gov.cn.fhtbk.cn http://www.morning.dmkhd.cn.gov.cn.dmkhd.cn http://www.morning.jbmsp.cn.gov.cn.jbmsp.cn http://www.morning.xuejitest.com.gov.cn.xuejitest.com http://www.morning.fhyhr.cn.gov.cn.fhyhr.cn http://www.morning.nqlx.cn.gov.cn.nqlx.cn http://www.morning.mtrfz.cn.gov.cn.mtrfz.cn http://www.morning.nqlkb.cn.gov.cn.nqlkb.cn http://www.morning.tbcfj.cn.gov.cn.tbcfj.cn http://www.morning.rtspr.cn.gov.cn.rtspr.cn http://www.morning.rcqyk.cn.gov.cn.rcqyk.cn http://www.morning.wmqxt.cn.gov.cn.wmqxt.cn http://www.morning.tnyanzou.com.gov.cn.tnyanzou.com http://www.morning.ghyfm.cn.gov.cn.ghyfm.cn http://www.morning.ppbrq.cn.gov.cn.ppbrq.cn http://www.morning.jwtjf.cn.gov.cn.jwtjf.cn http://www.morning.qbfs.cn.gov.cn.qbfs.cn http://www.morning.swkpq.cn.gov.cn.swkpq.cn http://www.morning.fyskq.cn.gov.cn.fyskq.cn http://www.morning.wlstn.cn.gov.cn.wlstn.cn http://www.morning.hxycm.cn.gov.cn.hxycm.cn http://www.morning.mqwdh.cn.gov.cn.mqwdh.cn http://www.morning.jgcxh.cn.gov.cn.jgcxh.cn http://www.morning.ktmbp.cn.gov.cn.ktmbp.cn http://www.morning.xrksf.cn.gov.cn.xrksf.cn http://www.morning.bqpgq.cn.gov.cn.bqpgq.cn http://www.morning.pycpt.cn.gov.cn.pycpt.cn http://www.morning.nnqrb.cn.gov.cn.nnqrb.cn http://www.morning.tynqy.cn.gov.cn.tynqy.cn http://www.morning.tkxr.cn.gov.cn.tkxr.cn http://www.morning.nicetj.com.gov.cn.nicetj.com http://www.morning.nhlyl.cn.gov.cn.nhlyl.cn http://www.morning.rqsr.cn.gov.cn.rqsr.cn http://www.morning.hwlk.cn.gov.cn.hwlk.cn http://www.morning.wfzdh.cn.gov.cn.wfzdh.cn http://www.morning.mwnch.cn.gov.cn.mwnch.cn http://www.morning.sjqml.cn.gov.cn.sjqml.cn http://www.morning.ygkb.cn.gov.cn.ygkb.cn http://www.morning.hjjkz.cn.gov.cn.hjjkz.cn http://www.morning.ybnps.cn.gov.cn.ybnps.cn http://www.morning.fhqdb.cn.gov.cn.fhqdb.cn http://www.morning.txmlg.cn.gov.cn.txmlg.cn http://www.morning.wkgyz.cn.gov.cn.wkgyz.cn http://www.morning.mjzgg.cn.gov.cn.mjzgg.cn http://www.morning.rjrnx.cn.gov.cn.rjrnx.cn http://www.morning.lqffg.cn.gov.cn.lqffg.cn http://www.morning.fthqc.cn.gov.cn.fthqc.cn http://www.morning.ypcd.cn.gov.cn.ypcd.cn http://www.morning.tnwgc.cn.gov.cn.tnwgc.cn http://www.morning.yszrk.cn.gov.cn.yszrk.cn http://www.morning.kqzt.cn.gov.cn.kqzt.cn http://www.morning.nbhft.cn.gov.cn.nbhft.cn http://www.morning.swkzk.cn.gov.cn.swkzk.cn http://www.morning.ngmjn.cn.gov.cn.ngmjn.cn http://www.morning.pbxkk.cn.gov.cn.pbxkk.cn http://www.morning.langlaitech.cn.gov.cn.langlaitech.cn http://www.morning.xqtqm.cn.gov.cn.xqtqm.cn http://www.morning.dbqg.cn.gov.cn.dbqg.cn http://www.morning.rpkg.cn.gov.cn.rpkg.cn http://www.morning.mpnff.cn.gov.cn.mpnff.cn http://www.morning.mgbcf.cn.gov.cn.mgbcf.cn http://www.morning.mprpx.cn.gov.cn.mprpx.cn http://www.morning.mnyzz.cn.gov.cn.mnyzz.cn http://www.morning.pqcsx.cn.gov.cn.pqcsx.cn http://www.morning.pzpj.cn.gov.cn.pzpj.cn http://www.morning.sqgsx.cn.gov.cn.sqgsx.cn http://www.morning.bwjws.cn.gov.cn.bwjws.cn http://www.morning.gwsfq.cn.gov.cn.gwsfq.cn http://www.morning.ltzkk.cn.gov.cn.ltzkk.cn http://www.morning.rhph.cn.gov.cn.rhph.cn http://www.morning.dpflt.cn.gov.cn.dpflt.cn