Ultra-fast WebSocket library built on uWebSockets.js with socket.io-like API
NanoSocket provides the world's fastest WebSocket implementation with an easy-to-use interface that developers already know and love.
|
|
# Using npm
npm install @sw3doo/nano-socket
# Using yarn
yarn add @sw3doo/nano-socket
# Using pnpm
pnpm add @sw3doo/nano-socket- Node.js: 16.0.0 or higher
- TypeScript: 4.5.0 or higher (for TypeScript projects)
- uWebSockets.js: Included as dependency
import { NanoSocket } from '@sw3doo/nano-socket';
// Create server with configuration
const server = new NanoSocket({
port: 3000,
compression: true,
cors: { origin: '*' }
});
// Handle connections
server.on('connection', (socket) => {
console.log(`β
Client connected: ${socket.id}`);
// Send welcome message
socket.emit('welcome', 'Hello from NanoSocket!');
// Handle messages
socket.on('message', (data) => {
console.log('π¨ Received:', data);
socket.emit('echo', data);
});
// Room management
socket.on('join-room', (roomName) => {
socket.join(roomName);
server.to(roomName).emit('user-joined', socket.id);
console.log(`π ${socket.id} joined room: ${roomName}`);
});
});
// Start server
server.listen().then(() => {
console.log('π NanoSocket server running on port 3000');
});import { NanoSocketClient } from '@sw3doo/nano-socket';
// Create client with auto-reconnection
const client = new NanoSocketClient('ws://localhost:3000', {
autoConnect: true,
reconnection: true,
reconnectionAttempts: 5,
reconnectionDelay: 1000
});
// Connection events
client.on('connect', () => {
console.log('π Connected to server!');
client.emit('message', 'Hello from client!');
client.emit('join-room', 'general');
});
client.on('disconnect', (reason) => {
console.log('β Disconnected:', reason);
});
// Message handling
client.on('welcome', (message) => {
console.log('π Welcome:', message);
});
client.on('echo', (data) => {
console.log('π Echo received:', data);
});
client.on('user-joined', (userId) => {
console.log(`π€ User ${userId} joined the room`);
});# Clone the repository
git clone https://github.com/sw3do/nano-socket.git
cd nano-socket
# Install dependencies
npm install
# Build the project
npm run build
# Run server (in one terminal)
npm run test:server
# Run client (in another terminal)
npm run test:clientconst server = new NanoSocket(options?: ServerOptions);ServerOptions:
port?: number- Server port (default: 3000)host?: string- Server host (default: '0.0.0.0')compression?: boolean- Enable compression (default: true)maxCompressedSize?: number- Max compressed message size (default: 64KB)maxBackpressure?: number- Max backpressure (default: 64KB)cors?: object- CORS configuration
listen(port?, host?): Promise Starts the server on specified port and host.
use(middleware): NanoSocket Adds middleware function for connection handling.
broadcast(event, ...args): void Broadcasts message to all connected clients.
to(room).emit(event, ...args): void Broadcasts message to all clients in a specific room.
close(): Promise Stops the server and closes all connections.
connectionCount: number Number of currently connected clients.
roomNames: string[] Array of all active room names.
connection- New client connectiondisconnect- Client disconnectionlistening- Server started listeningerror- Server errorclose- Server closed
const client = new NanoSocketClient(url: string, options?: ClientOptions);ClientOptions:
autoConnect?: boolean- Auto-connect on creation (default: true)reconnection?: boolean- Enable auto-reconnection (default: true)reconnectionAttempts?: number- Max reconnection attempts (default: 5)reconnectionDelay?: number- Delay between attempts in ms (default: 1000)timeout?: number- Connection timeout in ms (default: 20000)
connect(): Promise Connects to the WebSocket server.
disconnect(): void Disconnects from the server.
emit(event, ...args): boolean Sends message to the server.
on(event, handler): this Registers event handler.
off(event, handler?): this Removes event handler.
once(event, handler): this Registers one-time event handler.
connected: boolean Whether client is connected.
connectionState: ConnectionState Current connection state.
readyState: number WebSocket ready state.
serverUrl: string Server URL.
reconnectionAttempts: number Number of reconnection attempts made.
connect- Connected to serverdisconnect- Disconnected from serverconnecting- Attempting to connectreconnecting- Attempting to reconnectreconnect_failed- Failed to reconnecterror- Connection error
emit(event, ...args): void Sends message to this specific socket.
join(room): void Joins a room.
leave(room): void Leaves a room.
to(room).emit(event, ...args): void Broadcasts to room from this socket.
broadcast(event, ...args): void Broadcasts to all sockets except this one.
disconnect(): void Disconnects this socket.
NanoSocket is built for speed. Here's how it compares:
| Library | Messages/sec | Memory Usage | CPU Usage |
|---|---|---|---|
| NanoSocket | ~1,000,000+ | Low | Minimal |
| Socket.io | ~100,000 | Medium | Moderate |
| ws | ~500,000 | Low | Low |
Benchmarks run on Node.js 18.x, single core, 1KB messages
- uWebSockets.js: Built on the fastest WebSocket implementation
- Zero-copy: Minimal data copying in hot paths
- Efficient serialization: Optimized message handling
- Memory pooling: Reduced garbage collection pressure
- Native performance: C++ bindings for critical operations
βββββββββββββββββββ βββββββββββββββββββ
β Application β β Application β
βββββββββββββββββββ€ βββββββββββββββββββ€
β NanoSocket βββββΊβ NanoSocketClientβ
βββββββββββββββββββ€ βββββββββββββββββββ€
β uWebSockets.js β β ws β
βββββββββββββββββββ€ βββββββββββββββββββ€
β libuv/epoll β β libuv/epoll β
βββββββββββββββββββ βββββββββββββββββββ
Server Side Client Side
// Authentication middleware
server.use((socket, next) => {
const token = socket.handshake.auth.token;
if (validateToken(token)) {
socket.userId = getUserId(token);
next();
} else {
next(new Error('Authentication failed'));
}
});
// Logging middleware
server.use((socket, next) => {
console.log(`New connection from ${socket.remoteAddress}`);
next();
});// Join multiple rooms
socket.join(['room1', 'room2', 'room3']);
// Broadcast to specific rooms
server.to('room1').emit('announcement', 'Hello room1!');
server.to(['room1', 'room2']).emit('multi-room', 'Hello multiple rooms!');
// Broadcast to all except sender
socket.broadcast.emit('message', 'Hello everyone else!');// Server error handling
server.on('error', (error) => {
console.error('Server error:', error);
// Implement your error reporting here
});
// Client error handling
client.on('error', (error) => {
console.error('Client error:', error);
// Implement reconnection logic or user notification
});
// Connection-specific error handling
socket.on('error', (error) => {
console.error(`Socket ${socket.id} error:`, error);
socket.disconnect();
});We welcome contributions! Please see our Contributing Guide for details.
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Commit your changes:
git commit -m 'Add amazing feature' - Push to the branch:
git push origin feature/amazing-feature - Open a Pull Request
# Clone your fork
git clone https://github.com/sw3do/nano-socket.git
cd nano-socket
# Install dependencies
npm install
# Build and test
npm run build
npm testSee CHANGELOG.md for a detailed history of changes.
This project is licensed under the MIT License - see the LICENSE file for details.
- uWebSockets.js - The fastest WebSocket implementation
- Socket.io - Inspiration for the API design
- TypeScript Community - For excellent tooling and type definitions
- π Documentation: GitHub Wiki
- π Bug Reports: GitHub Issues
- π‘ Feature Requests: GitHub Issues
- π¬ Discussions: GitHub Discussions
- Check the documentation
- Search existing issues
- Create a new issue with detailed information
Made with β€οΈ by sw3do
β Star this repo if you find it useful!
id: string Unique socket identifier.
remoteAddress: string Client's remote address.
connected: boolean Whether socket is connected.
joinedRooms: string[] Array of rooms this socket has joined.
server.use((socket, next) => {
const token = socket.handshake?.auth?.token;
if (isValidToken(token)) {
next();
} else {
next(new Error('Authentication failed'));
}
});server.on('connection', (socket) => {
socket.on('join-game', (gameId) => {
socket.join(`game-${gameId}`);
server.to(`game-${gameId}`).emit('player-joined', {
playerId: socket.id,
playerCount: server.rooms.get(`game-${gameId}`)?.size || 0
});
});
});server.on('error', (error) => {
console.error('Server error:', error);
});
client.on('error', (error) => {
console.error('Client error:', error);
});NanoSocket is built on uWebSockets.js, which provides:
- 8x faster than ws library
- 2x faster than socket.io
- Minimal memory usage
- High concurrency support
- Built-in compression
NanoSocket is written in TypeScript and provides comprehensive type definitions:
import { NanoSocket, NanoSocketClient, ServerOptions, ClientOptions } from '@sw3doo/nano-socket';
const server: NanoSocket = new NanoSocket({
port: 3000,
compression: true
} as ServerOptions);Check the examples/ directory for complete implementation examples:
examples/server.ts- Full server implementationexamples/client.ts- Full client implementation