Replies: 1 comment
-
I am using this for persistent WS between pages. Maybe it is useful for you
import { readable } from 'svelte/store';
import { io } from 'socket.io-client';
let socket;
export const socketStore = readable(null, (set) => {
// Estoy en modo devel
// Uso hot.data para persistir el socket entre los hmr
if (import.meta.hot) {
if (!import.meta.hot.data.wsocket) {
socket = io();
import.meta.hot.data.wsocket = socket;
} else {
socket = import.meta.hot.data.wsocket;
}
// Estoy en prod
// Solo si no existe el socket, lo genero. Sino me empieza a duplicar en
// cada require de este modulo, ya que debería estar por fuera de este método exportado
// pero no puedo debido al modo desarrollo que lo necesito dentro
} else if (!socket) {
socket = io();
}
socket.on('eventFromServer', (event) => {
set(event);
});
socket.on('connect', () => {
set({ cmd: 'id', data: socket.id });
});
return () => {};
}); And in each <script>
import { socketStore } from '$lib/shared/WebSocket';
$: if ($socketStore) console.log('ws recibido'); // do your job
</script> In server side import { Server as wsServer } from 'socket.io';
export const wss = async (server) => {
const io = new wsServer(server, { serveClient: false });
// ...
io.on('connection', (ws) => {
logger.debug(`conectado: ${ws.id}`);
ws.on('disconnect', (reason) => {
logger.debug(`desconectado: ${reason}`);
});
});
} In import { wss } from './src/lib/server/wss.js';
const webSocketServer = {
name : 'webSocketServer',
configureServer(server) {
wss(server.httpServer);
}
};
/** @type {import('vite').UserConfig} */
const config = {
plugins : [
sveltekit(),
webSocketServer
]
}; If you are using external server, like express, import wss and add after handler (app.use(handler)), wss(server); |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I'm in the process of building a websocket (WS) powered UI (multiplayer game). My app is made up of several views (using views here to avoid terms like page and component). Furthermore, each of those views should be able to send and receive messages via a persistent WebSocket that is connected back to the game server when the app loads for the first time.
In Svelte, I would init my WS in my App component and either pass it around via props to child components or emit events from child to its parent and send messages via WS from App to the WS server. I believe I could even use the context API but haven't explore that option yet.
I would then conditionally render different components in App.svelte depending on the state of the app (or the view that needs to be shown to the user). As my app has 6 or 7 views, my conditional rendering code is getting hard to read so I thought I would give a try to Sveltekit to leverage its routing functionality + goto function to take the UI to the different views in my app.
In this setup, when I take user from / to view1 (via goto() ), I loose access to the client-side WS object that was connected to the server when the page first rendered on the browser.
I'm looking for a way to either store somewhere the WS object so that it's accessible when /view1 renders in the browser or to be able to emit some sort of event from the page backing my /view path but have not been able to find a way to do so.
Svelte context API and sveltekit stores are great for sharing state among components but sveltekit routes are backed by pages so I'm trying to to understand if I should stick to svelte for this use case or if I'm missing some feature that could help me here.
Beta Was this translation helpful? Give feedback.
All reactions