代码拉取完成,页面将自动刷新
<!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>sse</title>
</head>
<body>
<div>clientId: <span id="clientId"></span></div>
<button onclick="startSse()">开启SSE</button>
<button onclick="stopSse()">关闭SSE</button>
<button onclick="clearHistory()">清屏</button>
<div id="board"></div>
<script>
const uuid = generateClientId();
document.title = `sse-${uuid}`;
const uuidNode = document.createTextNode(uuid);
document.getElementById("clientId").appendChild(uuidNode);
let source = null;
function startSse() {
if(source != null) return;
source = new EventSource(`http://localhost:8080/sse/connect/${uuid}`, {withCredentials: false});
source.onopen = () => {
appendMsg("SSE连接成功")
console.log("SSE连接成功");
};
source.onmessage = event => {
try {
if (event.data && typeof event.data === "string") {
console.log(event.data)
appendMsg(event.data)
}
} catch (error) {
console.log("SSE消息异常", error);
}
};
// 监听错误
source.onerror = event => {
console.log(event);
source.close();
source = null;
appendMsg('Connection ERROR!')
};
}
/**
* 客户端主动断开SSE连接
*/
function stopSse() {
if(source == null) return;
source.close();
source = null;
appendMsg('SSE关闭成功')
}
/**
* 清除界面信息
*/
function clearHistory() {
const element = document.getElementById("board");
element.innerHTML = '';
}
/**
* 向界面追加信息
*/
function appendMsg(msg) {
const element = document.getElementById("board");
const div = document.createElement("div");
const now = new Date().toISOString();
const text = document.createTextNode(`${now} - ${msg}`);
div.appendChild(text)
element.appendChild(div);
}
/**
* 生成4位随机字符
*/
function generateClientId() {
return 'xxxx'.replace(/[xy]/g, function (c) {
const r = (Math.random() * 16) | 0,
v = c === "x" ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
</script>
</body>
</html>
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。