Connect
Establish a basic client connection to the KubeMQ server with the Node.js SDK, setting the address and client ID to start messaging.
Overview
Every KubeMQ application starts the same way: open a connection to the broker and prove it actually works before building anything on top of it. This tutorial is that first lesson — create a client, give it a stable identity, and confirm connectivity with a health check, so the pattern is muscle memory before you move on to real messaging.
KubeMQClient.create() is an async factory that takes an address and a clientId — the ID tags this connection in broker logs, subscriptions, and management views — and it resolves the gRPC channel and handshakes before returning, so a bad address surfaces immediately as a rejected Promise. client.ping() is still worth calling: it returns live server info (version, host, uptime) instead of just "connected," and client.state plus the stateChange event let you react to drops without polling. client.close() releases the underlying channel.
Gotchas: because create() connects eagerly, an unreachable broker delays the caller until the handshake times out — set connectionTimeoutSeconds deliberately rather than trusting the default; reusing the same client ID across running instances causes routing confusion on the broker; and forgetting client.close() in quick scripts is a common source of leaked connections under load.
Prerequisites
- KubeMQ server running on
localhost:50000 - Node.js SDK installed (
npm install kubemq-js)
Code
/**
* Example: Basic Client Connection
*
* Demonstrates creating a KubeMQ client with various connection options,
* verifying the connection with a ping, and inspecting connection state.
*
* Prerequisites:
* - KubeMQ server running on localhost:50000
*
* Run: npx tsx examples/connection/connect.ts
*/
import { KubeMQClient, ConnectionState, createConsoleLogger } from 'kubemq-js';
async function main(): Promise<void> {
// --- Option 1: Minimal connection (address only) ---
console.log('=== Minimal Connection ===');
// TODO: Replace with your KubeMQ server address
const minimal = await KubeMQClient.create({
address: 'localhost:50000',
clientId: 'js-connection-connect-client',
});
console.log('Client ID:', minimal.clientId);
console.log('Address:', minimal.address);
console.log('State:', minimal.state);
const info = await minimal.ping();
console.log('Server version:', info.version);
console.log('Server uptime:', info.serverUpTime, 'seconds');
await minimal.close();
// --- Option 2: Connection with custom options ---
console.log('\n=== Connection with Options ===');
const configured = await KubeMQClient.create({
address: 'localhost:50000',
clientId: 'js-connection-connect-configured-client',
connectionTimeoutSeconds: 15,
logger: createConsoleLogger('info'),
keepalive: {
timeMs: 10_000,
timeoutMs: 5_000,
permitWithoutCalls: true,
},
retry: {
maxRetries: 5,
initialBackoffMs: 500,
maxBackoffMs: 30_000,
multiplier: 2.0,
jitter: 'full',
},
});
console.log('State after create:', configured.state);
// Listen for connection state changes.
configured.on('stateChange', (state: ConnectionState) => {
console.log('State changed to:', state);
});
const configuredInfo = await configured.ping();
console.log('Server host:', configuredInfo.host);
await configured.close();
console.log('State after close:', configured.state);
}
main().catch(console.error);
// Expected output:
// === Minimal Connection ===
// Client ID: js-connection-connect-client
// Address: localhost:50000
// State: <connection-state>
// Server version: <version>
// Server uptime: <seconds> seconds
// === Connection with Options ===
// State after create: <connection-state>
// State changed to: <connection-state>
// Server host: <host>
// State after close: <connection-state>
How It Works
KubeMQClient.create()is the async factory — it resolves the gRPC channel and performs the initial handshake before returning, so any connection error surfaces as a rejected Promise.- Option 1 shows the minimal config (
address+clientId). Option 2 addskeepalive,retry, and a logger to demonstrate production-grade configuration. client.state(aConnectionStateenum) tracks the live connection status;client.on('stateChange', ...)lets you react to transitions without polling.client.ping()executes a round-trip gRPC health call and returnsServerInfo(version, host, uptime) — useful to verify the connection before sending messages.
Related
Was this page helpful?