afis.utils.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import * as net from 'net';
  2. import { interval, Subscription } from 'rxjs';
  3. export function connectToAfisJava(host: string, port: number, enableAutoPing = true): net.Socket {
  4. const client = new net.Socket();
  5. let reconnectTimeout: NodeJS.Timeout | null = null;
  6. let pingSubscription: Subscription | null = null;
  7. const connectToServer = () => {
  8. client.connect(port, host, () => {
  9. console.log(`✅ Connected to Afis Java Server at ${host}:${port}`);
  10. });
  11. };
  12. const scheduleReconnect = () => {
  13. if (!reconnectTimeout) {
  14. reconnectTimeout = setTimeout(() => {
  15. reconnectTimeout = null;
  16. connectToServer();
  17. }, 3000);
  18. }
  19. };
  20. // Initial connection attempt
  21. connectToServer();
  22. // Reconnection logic
  23. client.on('error', (err) => {
  24. console.error(`❌ TCP Error:`, err.message);
  25. scheduleReconnect();
  26. });
  27. client.on('close', (hadError) => {
  28. console.warn(`⚠️ Connection closed${hadError ? ' due to error' : ''}. Reconnecting...`);
  29. scheduleReconnect();
  30. });
  31. client.on('end', () => {
  32. console.warn('⚠️ Server closed the connection.');
  33. });
  34. // Incoming data handler
  35. client.on('data', (data) => {
  36. // console.log('📩 Received from server:', data.toString());c
  37. console.log(`Received 📩 From AfisServer` );
  38. });
  39. // Auto-message sending (optional)
  40. // if (enableAutoPing) {
  41. // pingSubscription = interval(3000).subscribe(() => {
  42. // if (client.destroyed) {
  43. // console.warn('⚠️ Cannot send: socket is destroyed.');
  44. // return;
  45. // }
  46. // const message = JSON.stringify({
  47. // pattern: 'get-user',
  48. // data: { id: 1 },
  49. // });
  50. // client.write(message + '\n');
  51. // });
  52. // }
  53. // Cleanup on destroy
  54. client.on('destroy', () => {
  55. if (pingSubscription) {
  56. pingSubscription.unsubscribe();
  57. pingSubscription = null;
  58. }
  59. });
  60. return client;
  61. }