/** * Example: Simple XMPP Client * Demonstrates basic XMPP client functionality */ const { Client } = require('@xmpp/client'); const { xml } = require('@xmpp/client'); const readline = require('readline'); // Configuration const config = { service: 'xmpp://localhost:5222', domain: 'localhost', username: 'user1', password: 'password' }; // Create client const client = new Client(config); // Setup readline for input const rl = readline.createInterface({ input: process.stdin, output: process.stdout, prompt: '> ' }); // Connection established client.on('online', async (address) => { console.log(`Connected as ${address.toString()}`); // Send presence await client.send(xml('presence')); console.log('\nCommands:'); console.log(' /send - Send a message'); console.log(' /presence [status] - Set presence'); console.log(' /quit - Disconnect'); console.log(''); rl.prompt(); }); // Handle incoming stanzas client.on('stanza', (stanza) => { if (stanza.is('message')) { const from = stanza.attrs.from; const body = stanza.getChildText('body'); if (body) { console.log(`\n[${from}]: ${body}`); rl.prompt(); } } else if (stanza.is('presence')) { const from = stanza.attrs.from; const type = stanza.attrs.type; const show = stanza.getChildText('show'); const status = stanza.getChildText('status'); if (type === 'unavailable') { console.log(`\n${from} is now offline`); } else { const state = show || 'available'; const statusText = status ? ` (${status})` : ''; console.log(`\n${from} is now ${state}${statusText}`); } rl.prompt(); } }); // Handle user input rl.on('line', async (line) => { const parts = line.trim().split(' '); const command = parts[0]; try { if (command === '/send' && parts.length >= 3) { const to = parts[1]; const message = parts.slice(2).join(' '); await client.send( xml('message', { type: 'chat', to }, xml('body', {}, message) ) ); console.log(`Sent to ${to}: ${message}`); } else if (command === '/presence') { const status = parts.slice(1).join(' '); const presence = xml('presence'); if (status) { presence.append(xml('status', {}, status)); } await client.send(presence); console.log('Presence updated'); } else if (command === '/quit') { await client.stop(); process.exit(0); } else if (command.startsWith('/')) { console.log('Unknown command'); } } catch (error) { console.error('Error:', error.message); } rl.prompt(); }); // Handle errors client.on('error', (err) => { console.error('Error:', err.message); }); // Start client console.log('Connecting to XMPP server...'); client.start().catch(console.error); // Handle process termination process.on('SIGINT', async () => { console.log('\nDisconnecting...'); await client.stop(); process.exit(0); });