This commit is contained in:
Miki 2023-12-20 13:17:43 +01:00
parent 1f96ed0930
commit e23ad2cbf2
11 changed files with 49 additions and 18 deletions

View file

@ -12,6 +12,35 @@
return now.toISOString();
}
function SSEMsg() {
const sse = new EventSource(`/api/sse?event=ping&event=pong`);
console.log('subscribe ping pong');
sse.onopen = () => {
console.log(`sse open ${now()}`);
msg = `sse open ${now()}`;
};
sse.addEventListener('ping', (e) => {
let Msg = JSON.parse(e.data);
msg = `ping: ${Msg.id} ${Msg.data} ${now()}`;
console.log(msg);
dping = Msg.id;
});
sse.addEventListener('pong', (e) => {
let Msg = JSON.parse(e.data);
msg = `pong: ${Msg.id} ${Msg.data} ${now()}`;
console.log(msg);
dpong = Msg.id;
});
return () => {
sse.close();
console.log(`sse closing ${Date.now()}`);
};
}
function Subscribe() {
const sse = new EventSource(`/api/sse`);
console.log('subscribe');
@ -64,10 +93,10 @@
};
}
onMount(() => {
const unsub = Subscribe();
return unsub;
});
// onMount(() => {
// const unsub = Subscribe();
// return unsub;
// });
async function newmsg() {
await fetch('/api/msg');
@ -103,4 +132,6 @@
<hr>
<button on:click={Subscribe}>SSE Msg</button>
<button on:click={SSEMsg}>SSE PingPong</button>
<br>
<button on:click={Subscribe}>SSE ALL</button>