Skip to content

aolose/sk-node-ws-demo

Repository files navigation

sk-node-ws-demo

sveltekit + adapter-node + socket.io

screenshot

try it on codesandbox.io

Very simple to use websockets at server side:

import {useServer} from "vite-sveltekit-node-ws";
import {Server} from 'socket.io'

useServer((server) => {
    const wsServer = new Server(server)
    wsServer.of('hello').on('connect', ws => {
        ws.on('hello', e => {
            ws.emit('echo', `echo: ${e}`)
        })
    })
},(path)=>/socket\.io|hello/.test(path))

Client side:

import {io} from "socket.io-client";
import {onMount} from "svelte";

onMount(()=>{
  io(`ws${location.origin.slice(4)}/hello`, {
      reconnectionDelayMax: 10000,
  });
});

You only need to configure the vite plugin:

import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
import ws from 'vite-sveltekit-node-ws';

export default defineConfig({
	plugins: [sveltekit(),ws()]
});

dev

pnpm run dev

prev

pnpm run prev

prod

pnpm run build
pnpm run prod