You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.7 KiB
HTML

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title></head>
<body>
<ul id="ul"></ul>
</body>
<script>
//生成li元素
function createLi(data) {
let li = document.createElement("li");
li.innerHTML = String(data.message);
return li;
}
//判断当前浏览器是否支持SSE
let source = ''
if (!!window.EventSource) {
source = new EventSource('http://127.0.0.1:3000/sse/ai/question/push?title=请你介绍一下SSE');
if (source.readyState === 0) {
//sseObj.readyState === EventSource.CONNECTING 也可以判断正在连接服务器
console.log('0:"正在连接服务器...');
}
} else {
throw new Error("当前浏览器不支持SSE")
}
//对于建立链接的监听
source.onopen = function (event) {
console.log(source.readyState);
console.log("长连接打开");
if (source.readyState === 1) {
// sseObj.readyState === EventSource.OPEN 也可以判断连接成功
let data = `SSE 连接成功,状态${source.readyState}, 对象${event}`;
console.log(data);
console.log("1:SSE 连接成功");
}
};
//对服务端消息的监听
source.onmessage =
function (event) {
console.log(JSON.parse(event.data));
console.log("收到长连接信息");
let li = createLi(JSON.parse(event.data));
document.getElementById("ul").appendChild(li)
};
// 接收消息,这个事件需要和后端保持一致哈
// 后端的事件名称sseEvent
// source.addEventListener("sseEvent", function (event) {
// const data = JSON.parse(event.data);
// //如果最后推送的是 'contDnd',说明推送已经完了。此时关闭连接
// if (data.content === 'contDnd') {
// source.close();
// if (source.readyState === 2) {
// // sseObj.readyState === EventSource.CLOSED 也可以判断连接已经关闭
// console.log('2连接已经关闭。', source.readyState);
// }
// console.log("end");
// } else {
// let li = createLi(JSON.parse(data.content));
// document.getElementById("ul").appendChild(li)
// }
// console.log("这次消息推送的内容event:", data.content);
// });
//对断开链接的监听
source.onerror = function (event) {
console.log(source.readyState);
console.log("长连接中断");
};
</script>
</html>