| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>SSE Example</title>
- <style>
- /* 修改后的 CSS */
- #sseOutput {
- display: inline-block;
- max-width: 600px; /* 控制最大宽度 */
- white-space: normal; /* 允许换行 (覆盖之前的 nowrap) */
- overflow-wrap: break-word; /* 长单词/URL强制换行 */
- vertical-align: top; /* 顶部对齐 */
- }
- </style>
- </head>
- <body>
- <h1>大模型 SSE 流媒体对话程序模块</h1>
- <span>问题:请问你可以理解人类的情感吗?</span>
- <br /><br />
- <!-- 移除行内 nowrap 样式 -->
- <span id="sseOutput">回答:</span>
-
- <script>
- var evtSource = new EventSource("https://emoon.com/sse.php?question=请问你可以理解人类的情感吗?");
-
- // 处理常规消息(保持原有逻辑)
- evtSource.onmessage = function(e) {
- try {
- const data = JSON.parse(e.data);
- if (data.choices?.[0]?.delta?.content) {
- document.getElementById("sseOutput").textContent += data.choices[0].delta.content;
- }
- } catch (err) {
- console.error("JSON解析失败:", err);
- }
- };
-
- // 新增end事件监听
- evtSource.addEventListener('end', function(e) {
- console.log("流式传输正常结束:", e.data);
- evtSource.close(); // 主动关闭连接
- }, false);
-
- // 错误处理优化
- evtSource.onerror = function(e) {
- if (e.eventPhase === EventSource.CLOSED) {
- console.log("连接已正常关闭");
- } else {
- console.error("连接异常:", e);
- }
- evtSource.close();
- };
- </script>
- </body>
- </html>
|