Back to Examples

PubNub Migration Example

This example demonstrates how to migrate from PubNub to OddSockets with minimal code changes using our PubNub compatibility layer. Most existing PubNub code will work unchanged!

Before vs After Comparison

Before (PubNub)

const pubnub = new PubNub({ publishKey: 'pub-c-xxxxxxxx...', subscribeKey: 'sub-c-xxxxxxxx...', userId: 'user123' });

After (OddSockets)

const pubnub = new PubNubCompat({ publishKey: 'ak_live_1234567890abcdef', subscribeKey: 'ak_live_1234567890abcdef', userId: 'user123' });

Why Migrate to OddSockets?

50% Lower Latency

Significantly faster message delivery than PubNub

No Per-Message Pricing

Transparent pricing without message-based charges

No Message Size Limits

Send messages of any size without restrictions

Built-in Analytics

Comprehensive analytics and monitoring included

Self-Hosted Option

Deploy on your own infrastructure for full control

Same API

Existing PubNub code works without changes

Complete Migration Example
JavaScript
const { PubNubCompat } = require('../src/index');

/**
 * PubNub to OddSockets Migration Example
 * 
 * This example shows how to migrate from PubNub to OddSockets with minimal code changes.
 * The PubNubCompat class provides a drop-in replacement for PubNub's JavaScript SDK.
 */

async function migrationExample() {
  console.log('šŸ”„ PubNub to OddSockets Migration Example');
  
  // BEFORE: PubNub configuration
  // const pubnub = new PubNub({
  //   publishKey: 'pub-c-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
  //   subscribeKey: 'sub-c-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
  //   userId: 'user123'
  // });
  
  // AFTER: OddSockets with PubNub compatibility
  const pubnub = new PubNubCompat({
    publishKey: 'ak_live_1234567890abcdef', // Your OddSockets API key
    subscribeKey: 'ak_live_1234567890abcdef', // Same as publishKey for OddSockets
    userId: 'user123',
    managerUrl: 'https://manager.oddsockets.com' // Optional: OddSockets manager URL
  });
  
  console.log('āœ… OddSockets client created with PubNub compatibility');
  
  // Add listeners (same as PubNub)
  pubnub.addListener({
    status: function(statusEvent) {
      console.log('šŸ“Š Status:', statusEvent.category);
      if (statusEvent.category === 'PNConnectedCategory') {
        console.log('šŸ”— Connected to OddSockets via PubNub compatibility layer');
      }
    },
    
    message: function(messageEvent) {
      console.log('šŸ“Ø Message received:', {
        channel: messageEvent.channel,
        message: messageEvent.message,
        publisher: messageEvent.publisher,
        timetoken: messageEvent.timetoken
      });
    },
    
    presence: function(presenceEvent) {
      console.log('šŸ‘¤ Presence event:', {
        channel: presenceEvent.channel,
        action: presenceEvent.action,
        uuid: presenceEvent.uuid,
        occupancy: presenceEvent.occupancy
      });
    }
  });
  
  // Subscribe to channels (same as PubNub)
  console.log('šŸ“” Subscribing to channels...');
  pubnub.subscribe({
    channels: ['migration-demo', 'chat-room'],
    withPresence: true
  });
  
  // Wait a moment for connection
  await new Promise(resolve => setTimeout(resolve, 2000));
  
  // Publish messages (same as PubNub)
  console.log('šŸ“¤ Publishing messages...');
  
  // Simple message
  await pubnub.publish({
    channel: 'migration-demo',
    message: 'Hello from OddSockets via PubNub compatibility!'
  });
  
  // Message with metadata
  await pubnub.publish({
    channel: 'migration-demo',
    message: {
      type: 'migration_test',
      content: 'This message was sent using PubNub-compatible API',
      timestamp: Date.now()
    },
    meta: {
      source: 'migration-example',
      version: '1.0'
    }
  });
  
  console.log('āœ… Messages published');
  
  // Get message history (same as PubNub)
  console.log('šŸ“š Fetching message history...');
  try {
    const historyResponse = await pubnub.history({
      channel: 'migration-demo',
      count: 10
    });
    
    console.log(`šŸ“– Retrieved ${historyResponse.messages.length} messages from history`);
    historyResponse.messages.forEach((msg, index) => {
      console.log(`  ${index + 1}. ${JSON.stringify(msg[0])} (${new Date(msg[1] / 10000).toISOString()})`);
    });
  } catch (error) {
    console.log('šŸ“š History not available yet (channel may be new)');
  }
  
  // Get presence information (same as PubNub)
  console.log('šŸ‘„ Fetching presence information...');
  try {
    const presenceResponse = await pubnub.hereNow({
      channels: ['migration-demo', 'chat-room']
    });
    
    console.log(`šŸ‘¤ Total occupancy: ${presenceResponse.totalOccupancy} across ${presenceResponse.totalChannels} channels`);
    
    Object.keys(presenceResponse.channels).forEach(channel => {
      const channelData = presenceResponse.channels[channel];
      console.log(`  šŸ“ŗ ${channel}: ${channelData.occupancy} users`);
    });
  } catch (error) {
    console.log('šŸ‘„ Presence information not available yet');
  }
  
  // Set user state (same as PubNub)
  console.log('šŸ”„ Setting user state...');
  try {
    await pubnub.setState({
      channels: ['migration-demo'],
      state: {
        status: 'migrating',
        from: 'pubnub',
        to: 'oddsockets',
        timestamp: Date.now()
      }
    });
    console.log('āœ… User state updated');
  } catch (error) {
    console.log('šŸ”„ State update not available yet');
  }
  
  // Demonstrate additional OddSockets features
  console.log('šŸš€ OddSockets provides additional benefits:');
  console.log('  • 50% lower latency than PubNub');
  console.log('  • No message size limits');
  console.log('  • No per-message pricing');
  console.log('  • Richer message metadata');
  console.log('  • Built-in analytics');
  console.log('  • Self-hosted option');
  
  // Migration checklist
  console.log('\nšŸ“‹ Migration Checklist:');
  console.log('  āœ… Replace PubNub import with OddSockets PubNubCompat');
  console.log('  āœ… Update publishKey/subscribeKey to OddSockets API key');
  console.log('  āœ… Add managerUrl configuration (optional)');
  console.log('  āœ… All existing PubNub code works unchanged');
  console.log('  āœ… Enjoy better performance and lower costs!');
  
  // Keep running for a bit
  console.log('\nā³ Keeping connection alive for 20 seconds...');
  setTimeout(() => {
    console.log('šŸ”Œ Disconnecting...');
    pubnub.disconnect();
    console.log('āœ… Migration example completed successfully!');
    console.log('šŸŽ‰ You\'ve successfully migrated from PubNub to OddSockets!');
    process.exit(0);
  }, 20000);
}

// Handle errors
process.on('unhandledRejection', (error) => {
  console.error('āŒ Unhandled error:', error);
  process.exit(1);
});

// Run the migration example
migrationExample().catch(console.error);