@aetherframework/websocket
v1.0.3
Published
Zero-dependency WebSocket server implementation for AetherJS
Downloads
164
Maintainers
Readme
Aether WebSocket API 🚀
High-Performance, Zero-Dependency WebSocket Server & Client for Node.js
Aether is a lightweight, robust, and highly efficient WebSocket implementation built from the ground up for Node.js. Unlike heavy frameworks that bundle unnecessary features, Aether focuses on raw speed, memory efficiency, and strict RFC 6455 compliance.
✨ Why Choose Aether?
⚡ Blazing Fast Performance Built with a custom binary frame parser (
FrameParser) and encoder (FrameEncoder), Aether minimizes garbage collection pressure and maximizes throughput. It handles thousands of concurrent connections with minimal CPU overhead.🪶 Zero Dependencies Aether relies only on Node.js built-in modules (
net,http,crypto,events). Nonpm installbloat, no security vulnerabilities from third-party packages, and a tiny footprint ideal for microservices and serverless environments.🛡️ Robust & Secure
- Strict Protocol Compliance: Fully adheres to RFC 6455.
- Memory Safety: Built-in protection against memory leaks via efficient buffer management.
- Error Resilience: Graceful handling of malformed frames, unexpected disconnections, and protocol errors.
Best For: Developers who need a reliable, lightweight, and transparent WebSocket solution without the baggage of large frameworks.
📦 Installation
Install Aether WebSocket via npm:
npm install aetherframework-websocket🚀 Quick Start
- Create a WebSocket Server
import { createWebSocketFactory } from 'aetherframework-websocket';
// Create a WebSocket factory instance
const factory = createWebSocketFactory({
port: 8080,
host: '0.0.0.0',
maxPayload: 1024 * 1024, // 1MB max message size
pingInterval: 30000, // Send ping every 30s
});
// Handle new connections
factory.on('connection', (connection) => {
console.log(`✅ New connection: ${connection.id}`);
// Send a welcome message
connection.socket.write(factory._encodeFrame(0x1, Buffer.from('Welcome to Aether!')));
// Handle incoming messages
factory.on('message', (conn, data, isBinary) => {
console.log(`📨 Received from ${conn.id}:`, data.toString());
// Echo back
conn.socket.write(factory._encodeFrame(0x1, Buffer.from('Echo: ' + data)));
});
// Handle disconnection
factory.on('close', (conn, code, reason) => {
console.log(`❌ Disconnected: ${conn.id} (Code: ${code})`);
});
});
// Start the server
async function start() {
try {
const server = await factory.createServer();
console.log(`🚀 Aether Server running on ws://${server.address.address}:${server.address.port}`);
} catch (error) {
console.error('Failed to start server:', error);
}
}
start();- Create a WebSocket Client
import { createWebSocketFactory } from 'aetherframework-websocket';
const factory = createWebSocketFactory();
async function connect() {
try {
const client = await factory.createClient('ws://localhost:8080');
console.log('✅ Connected to server');
// Listen for messages
factory.on('message', (conn, data, isBinary) => {
console.log('📨 Server says:', data.toString());
// Close connection after receiving
client.close(1000, 'Goodbye');
});
// Send a message
client.send('Hello Aether!');
} catch (error) {
console.error('Connection failed:', error);
}
}
connect();📚 API Reference
createWebSocketFactory Function
createWebSocketFactory(config)config.port(number): Server port (default:80).config.host(string): Server host (default:'0.0.0.0').config.maxPayload(number): Max message size in bytes (default:1048576).config.pingInterval(number): Milliseconds between pings (default:null).
Available Methods
| Method | Description | Returns |
| :--- | :--- | :--- |
| createServer(options) | Starts the HTTP/WebSocket server. | Promise<{ type, address, close }> |
| createClient(url, options) | Creates a WebSocket client connection. | Promise<{ id, socket, send, close }> |
| closeServer() | Gracefully shuts down the server. | Promise<void> |
| getStats() | Returns current server statistics. | Object |
Events
| Event | Callback Arguments | Description |
| :--- | :--- | :--- |
| connection | (connection) | Fired when a new client connects. |
| message | (connection, data, isBinary) | Fired when a message is received. |
| close | (connection, code, reason) | Fired when a connection closes. |
| error | (errorObj) | Fired on parsing or socket errors. |
| ping | (connection, payload) | Fired when a ping is received. |
| pong | (connection, payload) | Fired when a pong is received. |
🛠️ Advanced Configuration
Handling Binary Data Aether seamlessly handles both text and binary frames.
factory.on('message', (conn, data, isBinary) => {
if (isBinary) {
console.log('Received binary data:', data.length, 'bytes');
// Process Buffer directly
} else {
console.log('Received text:', data.toString());
}
});Custom Heartbeat Logic
If you disable pingInterval in config, you can implement custom health checks:
factory.on('connection', (conn) => {
conn.isAlive = true;
const interval = setInterval(() => {
if (!conn.isAlive) {
console.log('Terminating inactive connection');
conn.socket.destroy();
return clearInterval(interval);
}
conn.isAlive = false;
factory._sendPing(conn.socket);
}, 30000);
factory.on('pong', () => {
conn.isAlive = true;
});
});📊 Statistics & Monitoring
Use getStats() to monitor server health in real-time:
setInterval(() => {
const stats = factory.getStats();
console.log(`Active Connections: ${stats.connections}`);
console.log(`Uptime: ${stats.uptime}ms`);
console.log(`Memory RSS: ${stats.memory.rss} bytes`);
}, 10000);📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
Made with ❤️ by the Aether Team
