Real-world examples showing how to use the OddSockets Node.js SDK in server-side applications
Download Example Codeconst OddSockets = require('@oddsocketsai/nodejs-sdk');
const client = new OddSockets({
apiKey: 'ak_live_1234567890abcdef',
userId: 'server-user-123'
});
const channel = client.channel('my-channel');
// Subscribe to messages
await channel.subscribe((message) => {
console.log('Received:', message);
});
// Publish a message
await channel.publish({
text: 'Hello from Node.js server!',
timestamp: new Date().toISOString()
});
// Replace PubNub with OddSockets
const { PubNubCompat } = require('@oddsocketsai/nodejs-sdk');
const pubnub = new PubNubCompat({
publishKey: 'ak_live_1234567890abcdef',
subscribeKey: 'ak_live_1234567890abcdef',
userId: 'server123'
});
// Same API as PubNub!
pubnub.addListener({
message: function(messageEvent) {
console.log('Message:', messageEvent.message);
}
});
pubnub.subscribe({
channels: ['server-channel']
});
const express = require('express');
const OddSockets = require('@oddsocketsai/nodejs-sdk');
const app = express();
app.use(express.json());
// Initialize OddSockets
const client = new OddSockets({
apiKey: 'ak_live_1234567890abcdef'
});
// API endpoint to send messages
app.post('/api/send-message', async (req, res) => {
try {
const { channel, message } = req.body;
const oddSocketsChannel = client.channel(channel);
const result = await oddSocketsChannel.publish(message);
res.json({ success: true, result });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.listen(3000);
const OddSockets = require('@oddsocketsai/nodejs-sdk');
const client = new OddSockets({
apiKey: process.env.ODDSOCKETS_API_KEY,
userId: process.env.ODDSOCKETS_USER_ID || 'server-prod',
options: {
transports: ['websocket'], // WebSocket only
timeout: 10000, // 10 second timeout
reconnection: true, // Enable auto-reconnection
reconnectionAttempts: 10, // More attempts in production
maxReconnectionAttempts: 50 // Higher limit for production
}
});
// Production error handling
client.on('error', (error) => {
console.error('OddSockets error:', error);
});
// Graceful shutdown
process.on('SIGTERM', () => {
console.log('Shutting down gracefully...');
client.disconnect();
process.exit(0);
});
const OddSockets = require('@oddsocketsai/nodejs-sdk');
const client = new OddSockets({
apiKey: 'ak_live_1234567890abcdef'
});
// Publish multiple messages at once
const results = await client.publishBulk([
{ channel: 'notifications', message: 'User logged in' },
{ channel: 'analytics', message: { event: 'page_view' } },
{ channel: 'alerts', message: 'System status: OK' }
]);
results.forEach((result, index) => {
if (result.success) {
console.log(`Message ${index + 1} published successfully`);
} else {
console.error(`Message ${index + 1} failed:`, result.error);
}
});
FROM node:18-alpine
WORKDIR /app
# Copy package files
COPY package*.json ./
# Install dependencies
RUN npm ci --only=production
# Copy application code
COPY . .
# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s \
CMD node healthcheck.js || exit 1
# Expose port
EXPOSE 3000
# Start application
CMD ["node", "server.js"]