1 Star 0 Fork 0

a2cd/nestjs-sse-demo

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
sse.html 2.51 KB
一键复制 编辑 原始数据 按行查看 历史
a2cd 提交于 2024-05-28 16:46 +08:00 . docs
<!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>
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/a2cd/nestjs-sse-demo.git
[email protected]:a2cd/nestjs-sse-demo.git
a2cd
nestjs-sse-demo
nestjs-sse-demo
main

搜索帮助