Kalm API Documentation
Kalm is a socket optimization library that simplifies real-time communication with intelligent packet batching, multiplexing, and congestion control.
Lower resource footprint and better throughput than plain sockets through intelligent packet batching. Works seamlessly in both Node.js and browser environments with zero external dependencies.
Installation
Install Kalm and your preferred transport adapter:
npm install kalm
# Choose your transport adapter
npm install @kalm/tcp # For TCP connections
npm install @kalm/udp # For UDP datagrams
npm install @kalm/ws # For WebSocket
npm install @kalm/ipc # For IPC
Quick Start
Here's a simple example to get you started with a WebSocket chat application:
// Server
const Kalm = require('kalm');
const ws = require('@kalm/ws');
const server = Kalm.listen({
port: 9001,
transport: ws(),
});
server.on('connection', (client) => {
client.subscribe('chat', (data) => {
server.broadcast('chat', data);
});
});
// Client
const client = Kalm.connect({
host: '0.0.0.0',
port: 9001,
transport: ws(),
});
client.on('connect', () => {
client.subscribe('chat', (data) => {
console.log('Received:', data);
});
client.write('chat', { message: 'Hello!' });
});
kalm.listen()
kalm.listen(config: ServerConfig): Server
Creates and starts a Kalm server that listens for incoming connections.
Parameters
| Parameter | Type | Description |
|---|---|---|
config |
ServerConfig |
Server configuration object |
config.port |
number |
Port number to listen on |
config.host |
string |
Host address (optional, default: '0.0.0.0') |
config.transport |
TransportAdapter |
Transport adapter (tcp, udp, ws, ipc) |
config.routine |
BufferingRoutine |
Buffering strategy (optional) |
Returns
Server - A Kalm server instance
Example
const server = Kalm.listen({
port: 3000,
host: 'localhost',
transport: ws(),
routine: Kalm.routines.tick({ hz: 30 })
});
kalm.connect()
kalm.connect(config: ClientConfig): Client
Creates a Kalm client and connects to a server.
Parameters
| Parameter | Type | Description |
|---|---|---|
config |
ClientConfig |
Client configuration object |
config.host |
string |
Server hostname or IP address |
config.port |
number |
Server port number |
config.transport |
TransportAdapter |
Transport adapter (must match server) |
config.routine |
BufferingRoutine |
Buffering strategy (optional) |
config.socket |
any |
Custom socket object (optional) |
Returns
Client - A Kalm client instance
Example
const client = Kalm.connect({
host: 'localhost',
port: 3000,
transport: ws(),
routine: Kalm.routines.dynamic()
});
server.on()
server.on(event: string, callback: Function): void
Registers an event listener on the server.
Parameters
| Parameter | Type | Description |
|---|---|---|
event |
string |
Event name ('connection', 'ready', 'error') |
callback |
Function |
Event handler function |
Example
server.on('connection', (client) => {
console.log('Client connected');
});
server.on('ready', () => {
console.log('Server is ready');
});
server.on('error', (err) => {
console.error('Server error:', err);
});
server.broadcast()
server.broadcast(channel: string, data: any): void
Broadcasts a message to all connected clients subscribed to the specified channel.
Parameters
| Parameter | Type | Description |
|---|---|---|
channel |
string |
Channel name |
data |
any |
Data to broadcast (will be serialized) |
Example
server.broadcast('updates', {
type: 'notification',
message: 'Server maintenance in 5 minutes'
});
Server Events
Events emitted by the Kalm server:
connection
Callback: (client: Client) => void
Emitted when a new client connects to the server.
server.on('connection', (client) => {
console.log('New client connected');
});
ready
Callback: () => void
Emitted when the server is ready and listening for connections.
server.on('ready', () => {
console.log('Server listening on port 3000');
});
error
Callback: (error: Error) => void
Emitted when a server error occurs.
server.on('error', (err) => {
console.error('Server error:', err);
});
client.write()
client.write(channel: string, data: any): void
Sends data to the server on the specified channel.
Parameters
| Parameter | Type | Description |
|---|---|---|
channel |
string |
Channel name |
data |
any |
Data to send (will be serialized) |
Example
client.write('chat', {
user: 'John',
message: 'Hello World!'
});
client.subscribe()
client.subscribe(channel: string, callback: Function): void
Subscribes to a channel to receive messages.
Parameters
| Parameter | Type | Description |
|---|---|---|
channel |
string |
Channel name to subscribe to |
callback |
Function |
Callback for channel messages |
Example
client.subscribe('chat', (data) => {
console.log('Received:', data);
});
client.on()
client.on(event: string, callback: Function): void
Registers an event listener on the client.
Parameters
| Parameter | Type | Description |
|---|---|---|
event |
string |
Event name ('connect', 'disconnect', 'error', 'frame') |
callback |
Function |
Event handler function |
Example
client.on('connect', () => {
console.log('Connected to server');
});
client.subscribe('chat', (data) => {
console.log('Chat message:', data);
});
Client Events
Events emitted by the Kalm client:
connect
Callback: () => void
Emitted when the client successfully connects to the server.
client.on('connect', () => {
console.log('Successfully connected!');
});
disconnect
Callback: () => void
Emitted when the client disconnects from the server.
client.on('disconnect', () => {
console.log('Disconnected from server');
});
error
Callback: (error: Error) => void
Emitted when a client error occurs.
client.on('error', (err) => {
console.error('Client error:', err);
});
frame
Callback: (payload: Buffer) => void
Emitted when a raw frame payload is received.
client.on('frame', (payload) => {
console.log('Raw payload:', payload);
});
TCP Transport
TCP (Transmission Control Protocol) adapter for reliable, connection-oriented communication.
const tcp = require('@kalm/tcp');
const server = Kalm.listen({
port: 3000,
transport: tcp({
/** The maximum idle time for the connection before it hangs up (default: 30000) */
socketTimeout?: number
})
});
UDP Transport
UDP (User Datagram Protocol) adapter for fast, connectionless communication.
const udp = require('@kalm/udp');
const server = Kalm.listen({
port: 3000,
transport: udp({
/** The udp socket family (default: udp4) */
type?: 'udp4' | 'udp6'
/** The ip address that shows up when calling `local()` (default: '0.0.0.0') */
localAddr?: string
/** UDP reuse Address seting (default: false) */
reuseAddr?: boolean
/** The maximum idle time for the connection before it hangs up (default: 30000) */
socketTimeout?: number
})
});
WebSocket Transport
WebSocket adapter for browser-compatible bidirectional communication.
const ws = require('@kalm/ws');
const server = Kalm.listen({
port: 9001,
transport: ws({
/** The certificate file content for a secure socket connection, both this and `key` must be set */
cert?: string
/** The key file content for a secure socket connection, both this and `cert` must be set */
key?: string
/** Indicates wether a server or client should use wss:// protocol. Will throw an error if set without cert or key on the server */
secure?: boolean
/** The maximum idle time for the connection before it hangs up (default: 30000) */
socketTimeout: number
})
});
IPC Transport
IPC (Inter-Process Communication) adapter for same-machine process communication.
const ipc = require('@kalm/ipc');
const server = Kalm.listen({
port: 9001, // Not an actual port for IPC transport, instead is a suffix for the file-handler
transport: ipc({
/** The maximum idle time for the connection before it hangs up (default: 30000) */
socketTimeout: 30000,
/** The prefix to use for file handler location. Final handler is ${path + port}
Ex: '/tmp/app.socket-9001' for Mac and Linux or 'C:\Windows\Temp\app.socket-9001' on Windows
*/
path: '/tmp/app.socket-'
})
});
realtime()
Kalm.routines.realtime({ deferred?: boolean }): BufferingRoutine
Immediate transmission with minimal latency. Messages are sent as soon as they are written.
Parameters
| Parameter | Type | Description |
|---|---|---|
deferred |
boolean |
(Optional) Defers emit until the next UV cycle. Can prevent blocking of the execution thread |
Example
const client = Kalm.connect({
host: 'localhost',
port: 3000,
transport: tcp(),
routine: Kalm.routines.realtime({
deferred: false
})
});
tick()
Kalm.routines.tick({ hz: number, seed?: number }): BufferingRoutine
Fixed-frequency dispatch. Batches messages and sends them at regular intervals.
Parameters
| Parameter | Type | Description |
|---|---|---|
hz |
number |
Frequency in Hz (e.g., 5 Hz = 200ms intervals) |
seed |
number |
(Optional) A seed can be provided to synchronize multiple servers. Ex: a main node will pass an ISO timestamp to other nodes. |
Example
const client = Kalm.connect({
host: 'localhost',
port: 3000,
transport: tcp(),
routine: Kalm.routines.tick({ hz: 30 }) // 30 times per second
});
dynamic()
Kalm.routines.dynamic({ maxInterval: number, maxPackets?: number, maxBytes?: number }): BufferingRoutine
Adaptive buffering based on traffic patterns. Automatically adjusts batching strategy.
Parameters
| Parameter | Type | Description |
|---|---|---|
maxInterval |
number |
Maximum interval between emits in milliseconds |
maxPackets |
number |
(Optional) Maximum number of messages in the queue. |
maxBytes |
number |
(Optional) Maximum number of total bytes in the queue across all messages. |
Example
const client = Kalm.connect({
host: 'localhost',
port: 3000,
transport: tcp(),
routine: Kalm.routines.dynamic({
maxInterval: 50, // Sends the payload if 50ms elapsed since the last emit...
maxPackets: 3, // OR if there are 3 or more messages in the payload...
maxBytes: 3500 // OR if the size of the payload reaches 3500 bytes.
})
});
ServerConfig
Configuration object for creating a Kalm server.
interface ServerConfig {
port: number; // Port to listen on
host?: string; // Host address (default: '0.0.0.0')
transport: TransportAdapter; // Transport adapter
routine?: BufferingRoutine; // Buffering strategy (optional)
}
ClientConfig
Configuration object for creating a Kalm client.
interface ClientConfig {
host: string; // Server hostname or IP
port: number; // Server port
transport: TransportAdapter; // Transport adapter
routine?: BufferingRoutine; // Buffering strategy (optional)
socket?: any; // Custom socket object (optional)
}
TransportAdapter
Transport adapter for different protocols. Available adapters:
@kalm/tcp- TCP socket connections@kalm/udp- UDP datagram protocol@kalm/ws- WebSocket support@kalm/ipc- Inter-process communication
BufferingRoutine
Buffering strategy for packet batching. Available routines:
Kalm.routines.realtime()- Immediate transmissionKalm.routines.tick({ hz })- Fixed-frequency dispatchKalm.routines.dynamic()- Adaptive buffering