@eelnet/client
v2.1.1
Published
Peer-to-peer networking library for EelNet
Downloads
514
Maintainers
Readme
@eelnet/client
eelnet.dev | Free P2P networking for real-time apps
Client for the EelNet peer-to-peer networking service. Provides a simple API for real-time collaborative applications.
Features
- Simple API - Just
connect()anddisconnect()- all network negotiation handled automatically - Automatic Peer Management - Peers are discovered and connected when joining
- Reconnection - Built-in exponential backoff reconnection to the service
- TypeScript - Full type definitions included
- Cross-Platform - Works in browsers and Node.js.
Installation
npm install @eelnet/clientQuick Start
import { EelNet } from '@eelnet/client';
// Create client with your API key
const client = new EelNet({
apiKey: 'eel_live_your_api_key',
});
// Listen for events
client.on('message', (peerId, data) => {
console.log(`Message from ${peerId}:`, data);
});
client.on('peerJoined', (peerId) => {
console.log(`Peer ${peerId} joined the room`);
});
client.on('peerLeft', (peerId) => {
console.log(`Peer ${peerId} left`);
});
// Connect to a room - returns your peer ID and list of peers in the room
const { peerId, peers } = await client.connect('my-game-room');
console.log(`Connected as ${peerId}, ${peers.length} peers in room`);
// Wait for all WebRTC connections to be established
await client.waitForPeers();
console.log('All peers connected and ready!');
// Send data to everyone
client.broadcast({ type: 'hello', name: 'Player1' });
// When done
await client.disconnect();API Reference
Constructor
new EelNet(config: EelNetConfig)EelNetConfig
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| apiKey | string | required | API key for authentication |
| autoReconnect | boolean | true | Enable automatic reconnection |
| maxReconnectAttempts | number | 5 | Max reconnection attempts |
| reconnectBaseDelay | number | 1000 | Base delay (ms) for exponential backoff |
| dataChannel.ordered | boolean | false | Deliver messages in order |
| dataChannel.maxRetransmits | number | undefined | Max retransmits (undefined = reliable, 0 = unreliable) |
| debug | boolean | false | Enable debug logging |
Methods
connect(room: string): Promise<ConnectResult>
Connect to the server and join a room. Returns connection info including your peer ID and the list of peers already in the room. Automatically begins establishing P2P connections with all peers.
const { peerId, peers } = await client.connect('lobby');
console.log(`Joined as ${peerId}, ${peers.length} peers in room`);ConnectResult:
| Property | Type | Description |
|----------|------|-------------|
| peerId | string | Your assigned peer ID |
| peers | string[] | Peer IDs already in the room (WebRTC connections pending) |
waitForPeers(): Promise<void>
Wait for all pending peer connections to be established. Call this after connect() or after a peerJoined event to ensure all WebRTC data channels are open and ready for communication.
// After initial connection
const { peerId, peers } = await client.connect('lobby');
console.log(`Joining with ${peers.length} peers...`);
await client.waitForPeers();
console.log('All peers connected!');
// When a new peer joins mid-game
client.on('peerJoined', async (newPeerId) => {
console.log(`${newPeerId} is connecting...`);
await client.waitForPeers();
console.log(`${newPeerId} is ready!`);
});disconnect(): Promise<void>
Disconnect from the room and server. Closes all peer connections.
await client.disconnect();broadcast(data: unknown): void
Send data to all connected peers.
client.broadcast({ type: 'position', x: 100, y: 200 });sendTo(peerId: string, data: unknown): boolean
Send data to a specific peer. Returns true if sent, false if peer not connected.
const sent = client.sendTo('peer_abc123', { type: 'whisper', text: 'Hello!' });getPeers(): string[]
Get list of connected peer IDs.
const peers = client.getPeers();
console.log(`Connected to ${peers.length} peers`);getPeerId(): string | null
Get your own peer ID (assigned by the server).
console.log(`My peer ID: ${client.getPeerId()}`);getRoom(): string | null
Get the current room name.
getState(): ConnectionState
Get the current connection state: 'disconnected', 'connecting', 'connected', or 'reconnecting'.
hasPendingPeers: boolean
Check if there are any pending peer connections (WebRTC handshakes in progress).
pendingPeerCount: number
Get the number of pending peer connections.
on(event, handler): void
Register an event handler.
off(event, handler): void
Remove an event handler.
Events
| Event | Handler Signature | Description |
|-------|-------------------|-------------|
| message | (peerId: string, data: unknown) => void | Received data from a peer |
| peerJoined | (peerId: string) => void | A peer joined the room |
| peerLeft | (peerId: string) => void | A peer left or disconnected |
| peerConnected | (peerId: string) => void | Data channel opened with peer |
| stateChange | (state: ConnectionState) => void | Connection state changed |
| error | (error: EelNetError) => void | An error occurred |
| disconnected | (reason: string) => void | Disconnected from server |
| reconnecting | (attempt: number) => void | Attempting to reconnect |
Handling Reconnection
const client = new EelNet({
apiKey: 'eel_live_xxx',
autoReconnect: true,
maxReconnectAttempts: 10,
});
client.on('disconnected', (reason) => {
showNotification(`Disconnected: ${reason}`);
});
client.on('reconnecting', (attempt) => {
showNotification(`Reconnecting... (attempt ${attempt})`);
});
client.on('stateChange', (state) => {
if (state === 'connected') {
hideNotification();
}
});Data Channel Configuration
The ordered and maxRetransmits properties are independent and control different aspects:
ordered: Whether messages must arrive in the order sentmaxRetransmits: How many times to retry failed messages (undefined = infinite)
Common Configurations
Real-time games (UDP-like) - Fast, may lose data:
{
dataChannel: {
ordered: false, // Don't wait for lost packets
maxRetransmits: 0, // Don't retry
}
}Chat or turn-based games (TCP-like) - Reliable and ordered:
{
dataChannel: {
ordered: true, // Maintain message order
// maxRetransmits not set = retry forever (reliable)
}
}Advanced: Reliable but unordered - All messages arrive, but order doesn't matter:
{
dataChannel: {
ordered: false,
// maxRetransmits not set = retry forever (reliable)
}
}Error Handling
import { EelNet, EelNetError } from '@eelnet/client';
client.on('error', (error: EelNetError) => {
console.error(`Error: ${error.message}`);
if (error.code) {
console.error(`Code: ${error.code}`);
}
if (error.peerId) {
console.error(`Related to peer: ${error.peerId}`);
}
});
try {
await client.connect('room');
} catch (error) {
if (error instanceof EelNetError) {
handleConnectionError(error);
}
}TypeScript
Full TypeScript support with exported types:
import type {
EelNetConfig,
EelNetEvents,
ConnectionState,
ConnectResult,
EelNetError,
} from '@eelnet/client';Browser Support
Works in all modern browsers that support WebRTC:
- Chrome 56+
- Firefox 44+
- Safari 11+
- Edge 79+
License
MIT
