A TypeScript-based Socket class that integrates Socket.IO with Svelte's reactivity system for real-time communication, featuring Svelte context for instance sharing across components.
Install dependencies:
npm install
Start the Socket.IO server:
cd server
npm install
npm start
Start the Svelte development server:
npm run dev
Open your browser to view the real-time Socket.IO demo.
The CLI is your trusty sidekick for monitoring server activity and sending commands faster than you can say "byte me!" Here's the lowdown on the stellar commands at your disposal:
Command | Function | Geeky Description |
---|---|---|
P | Ping Clients | Sends a ping to all connected clients. |
B | Broadcast to Clients | Broadcast a message to all clients. |
Q | Quit | Time to shut down the warp drive and exit gracefully. |
├── src/
│ ├── lib/
│ │ ├── Socket.ts # Main Socket class with Svelte context integration
│ │ ├── SocketContext.svelte # Showing how to pass the connection to components
│ │ └── SocketExample.svelte # Demo component showcasing socket functionality
│ ├── App.svelte # Main app component
├── server/
│ ├── server.js # Socket.IO server implementation
│ └── package.json # Server dependencies
└── README.md # This file
// In a parent component (e.g., src/routes/+layout.svelte)
import { Socket } from '$lib/Socket.ts';
const socket = new Socket('http://localhost:3001');
// or
const socket = new Socket('http://localhost:3001', socketConfig);
await socket.connect(); // Initializes connection and sets context
import { Socket } from '$lib/Socket.ts';
let socketInstance: Socket = Socket.getSocketContext(); // Retrieve during init
socketInstance.on('message', (data) => {
console.log('Received:', data);
});
socketInstance.send('message', { text: 'Hello World!' });
console.log('Connection status:', socketInstance.getStatus().connected);
Note: Set the socket in a parent component during initialization (e.g., <script>
block of +layout.svelte
). Retrieve using Socket.getSocketContext
in child components during initialization and assign to a variable for use in event handlers to comply with Svelte's lifecycle requirements.
Protecting sensitive information, such as your server URL, is crucial for maintaining the security of your application. By leveraging Vite's environment variables, you can securely manage and obscure your server URL, ensuring it remains hidden from client-side code.
Vite provides a clean way to define environment variables using import.meta.env
. This allows you to reference your server URL without hardcoding it in your application code.
Below is an example of how to use Vite’s environment variables to define a WebSocket URL in your JavaScript code:
// Initialize a WebSocket connection using the Vite environment variable
const socket = new Socket(import.meta.env.VITE_SOCKET_URL);
To define the server URL, configure the define
property in your Vite configuration file (vite.config.js
). This approach ensures the URL is injected at build time and remains secure.
import { defineConfig } from 'vite';
import sveltekit from '@sveltekit/vite-plugin-sveltekit';
// Vite configuration
export default defineConfig({
plugins: [sveltekit()],
css: {
postcss: './postcss.config.js'
},
define: {
'import.meta.env.VITE_SOCKET_URL': JSON.stringify('http://localhost:3000')
}
});
.env
Files: Instead of hardcoding the URL in vite.config.js
, store it in a .env
file (e.g., VITE_SOCKET_URL=http://localhost:3000
) and load it using import.meta.env.VITE_SOCKET_URL
. This keeps sensitive data out of version control.VITE_
are only exposed to the client when necessary, as Vite makes them available in the browser..env.production
file for deployment to point to your live server (e.g., https://api.yourdomain.com
).By following these steps, you can securely manage your server URL and maintain a professional, robust development workflow.
The included demo (SocketExample.svelte
) demonstrates:
reconnectionAttempts
, timeout
) and context key (socketContext
) via the config object.status
object for connection state, errors, and timestamps.message
, user-joined
) and internal events (connected
, disconnected
, etc.).connect
, send
, on
, off
, once
, getStatus
, isConnected
, getSocket
, clearMessages
, destroy
, and getSocketContext
.setContext
in parent components and getSocketContext
in children for shared socket access.Contributions are welcome via issues and pull requests. This project showcases:
MIT License - free to use in your projects