1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- 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;
- }
|