import * as net from 'net'; import { interval, Subscription } from 'rxjs'; export function connectToAfisJava(host: string, port: number, enableAutoPing = true): net.Socket { const client = new net.Socket(); let reconnectTimeout: NodeJS.Timeout | null = null; let pingSubscription: Subscription | null = null; const connectToServer = () => { client.connect(port, host, () => { console.log(`✅ Connected to Afis Java Server at ${host}:${port}`); }); }; const scheduleReconnect = () => { if (!reconnectTimeout) { reconnectTimeout = setTimeout(() => { reconnectTimeout = null; connectToServer(); }, 3000); } }; // Initial connection attempt connectToServer(); // Reconnection logic client.on('error', (err) => { console.error(`❌ TCP Error:`, err.message); scheduleReconnect(); }); client.on('close', (hadError) => { console.warn(`⚠️ Connection closed${hadError ? ' due to error' : ''}. Reconnecting...`); scheduleReconnect(); }); client.on('end', () => { console.warn('⚠️ Server closed the connection.'); }); // Incoming data handler client.on('data', (data) => { // console.log('📩 Received from server:', data.toString());c console.log(`Received 📩 From AfisServer` ); }); // Auto-message sending (optional) // if (enableAutoPing) { // pingSubscription = interval(3000).subscribe(() => { // if (client.destroyed) { // console.warn('⚠️ Cannot send: socket is destroyed.'); // return; // } // const message = JSON.stringify({ // pattern: 'get-user', // data: { id: 1 }, // }); // client.write(message + '\n'); // }); // } // Cleanup on destroy client.on('destroy', () => { if (pingSubscription) { pingSubscription.unsubscribe(); pingSubscription = null; } }); return client; }