+sse test

This commit is contained in:
Miki 2023-12-19 16:56:10 +01:00
parent 19cf309392
commit 2289aa31fd
61 changed files with 2250 additions and 0 deletions

12
sse/fe/src/app.html Normal file
View file

@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>

1
sse/fe/src/lib/index.js Normal file
View file

@ -0,0 +1 @@
// place files you want to import through the `$lib` alias in this folder.

View file

@ -0,0 +1,3 @@
export const prerender = true;
export const ssr = false;
export const trailingSlash = 'always';

View file

@ -0,0 +1,2 @@
<h1>Welcome to SvelteKit</h1>
<p>Visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to read the documentation</p>

View file

@ -0,0 +1,81 @@
<script>
import { onMount } from'svelte';
$: msg = "";
function now() {
const now = new Date(Date.now());
return now.toISOString();
}
function Subscribe() {
const sse = new EventSource(`/api/sse`);
console.log('subscribe');
sse.onopen = () => {
console.log(`sse open ${now()}`);
msg = `sse open ${now()}`;
};
sse.onerror = () => {
console.log(`sse error ${now()}`);
if (sse.readyState === EventSource.CONNECTING) {
console.log(`sse reconnecting ${now()}`);
}
msg = `sse error ${now()}`;
};
sse.onmessage = (e) => {
let Msg = JSON.parse(e.data);
console.log(`received: ${JSON.stringify(Msg)}`);
msg = `received: ${JSON.stringify(Msg)} ${Date.now()}`;
};
sse.addEventListener('ping', (e) => {
console.log(`ping: ${e.data}`);
msg = `ping: ${e.data} ${Date.now()}`;
});
sse.addEventListener('pong', (e) => {
console.log(`pong: ${e.data}`);
msg = `pong: ${e.data} ${Date.now()}`;
});
sse.addEventListener('message', (e) => {
console.log(`message: ${e.data}`);
msg = `message: ${e.data} ${Date.now()}`;
})
return () => {
sse.close();
console.log(`sse closing ${Date.now()}`);
};
}
onMount(() => {
const unsub = Subscribe();
return unsub;
});
async function newmsg() {
await fetch('/api/msg');
}
async function ping() {
await fetch('/api/ping');
}
async function pong() {
await fetch('/api/pong');
}
</script>
<h1>{msg}</h1>
<button on:click={newmsg}>send Msg</button>
<button on:click={ping}>send Ping</button>
<button on:click={pong}>send Pong</button>