Closed thonkinator closed 1 year ago
I reproduced your code and it works for me... Did you build the app? It doesn't run in dev mode
// hooks.server.ts
import type { WebSocketHandler } from "svelte-adapter-bun";
export const handleWebsocket: WebSocketHandler = {
open(ws) {
ws.send("test");
console.log("ws opened");
},
upgrade(request, upgradeFn) {
const url = new URL(request.url);
return url.pathname.startsWith("/ws") ? upgradeFn(request) : false;
},
message(ws, message) {
ws.send(message);
console.log("ws message", message);
},
};
// +page.svelte
<script>
import { onMount } from "svelte";
import { page } from "$app/stores";
onMount(() => {
const socket = new WebSocket(`ws://${$page.url.host}/ws`);
socket.addEventListener("message", (e) => {
console.log(e.data);
});
socket.addEventListener("open", () => {
socket.send("Hello!");
});
});
</script>
<h1>Welcome to SvelteKit</h1>
<p>Visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to read the documentation</p>
oh sorry, I didn't see that it doesn't work in devmode. building it works. thanks!
Whenever I try to open a WebSocket from the client to the server, if I use
ws://
the connection just stalls indefinitely, and if I usewss://
I getWebSocket connection to wss://localhost:5173/ws failed:
on the client, and(node:5790) Warning: An error event has already been emitted on the socket. Please use the destroy method on the socket while handling a 'clientError' event.
on the server. Here's my+page.svelte
:And here's my
hooks.server.ts
: