sse.html 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <html lang="en">
  2. <head>
  3. <meta charset="UTF-8">
  4. <title>SSE Example</title>
  5. <style>
  6. /* 修改后的 CSS */
  7. #sseOutput {
  8. display: inline-block;
  9. max-width: 600px; /* 控制最大宽度 */
  10. white-space: normal; /* 允许换行 (覆盖之前的 nowrap) */
  11. overflow-wrap: break-word; /* 长单词/URL强制换行 */
  12. vertical-align: top; /* 顶部对齐 */
  13. }
  14. </style>
  15. </head>
  16. <body>
  17. <h1>大模型 SSE 流媒体对话程序模块</h1>
  18. <span>问题:请问你可以理解人类的情感吗?</span>
  19. <br /><br />
  20. <!-- 移除行内 nowrap 样式 -->
  21. <span id="sseOutput">回答:</span>
  22. <script>
  23. var evtSource = new EventSource("https://emoon.com/sse.php?question=请问你可以理解人类的情感吗?");
  24. // 处理常规消息(保持原有逻辑)
  25. evtSource.onmessage = function(e) {
  26. try {
  27. const data = JSON.parse(e.data);
  28. if (data.choices?.[0]?.delta?.content) {
  29. document.getElementById("sseOutput").textContent += data.choices[0].delta.content;
  30. }
  31. } catch (err) {
  32. console.error("JSON解析失败:", err);
  33. }
  34. };
  35. // 新增end事件监听
  36. evtSource.addEventListener('end', function(e) {
  37. console.log("流式传输正常结束:", e.data);
  38. evtSource.close(); // 主动关闭连接
  39. }, false);
  40. // 错误处理优化
  41. evtSource.onerror = function(e) {
  42. if (e.eventPhase === EventSource.CLOSED) {
  43. console.log("连接已正常关闭");
  44. } else {
  45. console.error("连接异常:", e);
  46. }
  47. evtSource.close();
  48. };
  49. </script>
  50. </body>
  51. </html>