apiSSE.html 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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>问题:The highest mountain in the world is Mount Everest.What is the second?</span>
  19. <br /><br />
  20. <!-- 移除行内 nowrap 样式 -->
  21. <span id="sseOutput">回答:</span>
  22. <script>
  23. var evtSource = new EventSource("https://open.emoon.com/apiSSE.php?token=de0f72abec0d6f6f6fa366b91ce9b22c");
  24. // 处理常规消息(保持原有逻辑)
  25. evtSource.onmessage = function(e) {
  26. try {
  27. const data = JSON.parse(e.data);
  28. if (data.choices?.[0]?.delta?.content) {
  29. console.log(data.choices[0].delta.content);
  30. document.getElementById("sseOutput").textContent += data.choices[0].delta.content;
  31. }
  32. } catch (err) {
  33. console.error("JSON解析失败:", err);
  34. }
  35. };
  36. // 新增end事件监听
  37. evtSource.addEventListener('end', function(e) {
  38. console.log("流式传输正常结束:", e.data);
  39. evtSource.close(); // 主动关闭连接
  40. }, false);
  41. // 错误处理优化
  42. evtSource.onerror = function(e) {
  43. if (e.eventPhase === EventSource.CLOSED) {
  44. console.log("连接已正常关闭");
  45. } else {
  46. console.error("连接异常:", e);
  47. }
  48. evtSource.close();
  49. };
  50. // 鉴定请求接口权限
  51. evtSource.addEventListener('verify', function(e) {
  52. console.log("参数验证失败:", e.data);
  53. evtSource.close(); // 主动关闭连接
  54. }, false);
  55. </script>
  56. </body>
  57. </html>