gornostay25 / svelte-adapter-bun

A SvelteKit adapter for Bun
MIT License
537 stars 34 forks source link

can't use WebSocket hook #24

Closed thonkinator closed 1 year ago

thonkinator commented 1 year ago

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 use wss:// I get WebSocket 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:

<script lang="ts">
    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);
        });
    });
</script>

<h1>Welcome to SvelteKit</h1>
<p>Visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to read the documentation</p>

And here's my hooks.server.ts:

import type { WebSocketHandler } from "svelte-adapter-bun";

export const handleWebsocket: WebSocketHandler = {
    open(ws) {
        ws.send("test");
    },
    upgrade(request, upgradeFn) {
        const url = new URL(request.url);
        return url.pathname.startsWith("/ws") ? upgradeFn(request) : false;
    },
    message(ws, message) {
        ws.send(message);
    },
};
gornostay25 commented 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>

image image

thonkinator commented 1 year ago

oh sorry, I didn't see that it doesn't work in devmode. building it works. thanks!