Browse Source

Set up custom TCP connection with Java TCP version.

enzo 1 week ago
parent
commit
cd4c04468f

+ 4 - 1
.gitmodules

@@ -1,3 +1,6 @@
 [submodule "apps/fis-fingerprint/Fis-Fingerprint"]
 	path = apps/fis-fingerprint/Fis-Fingerprint
-	url = https://git.swopt.com/enzo/Fis-Fingerprint.git
+	url = https://git.swopt.com/enzo/Fis-Fingerprint.git
+[submodule "apps/fis-verification/Fis-VerificationModule"]
+	path = apps/fis-verification/Fis-VerificationModule
+	url = https://git.swopt.com/enzo/Fis-VerificationModule.git

+ 1 - 0
apps/fis-verification/Fis-VerificationModule

@@ -0,0 +1 @@
+Subproject commit 65e84e2d26a1c9c5918e3f2fffc09e3f829c935e

+ 2 - 1
apps/fis-verification/src/fis-verification.controller.ts

@@ -14,7 +14,8 @@ export class FisVerificationController {
 
   @EventPattern(`eventTest`)
   eventTest(message: string): void {
-    console.log(`Hello there. Just Responding to Event pattern`)
+    console.log(`Hello there. Just Responding to Event pattern.`)
   }
+
 }
 

+ 17 - 1
apps/fis-verification/src/fis-verification.module.ts

@@ -19,7 +19,23 @@ import { ConfigModule, ConfigService } from '@nestjs/config';
           transport: Transport.TCP,
           options: {
             host: configService.get<string>(`sampleApp.host`) as string,
-            port: configService.get<number>(`sampleApp.tcpPort`) as number
+            port: configService.get<number>(`sampleApp.tcpPort`) as number,
+            retryAttempts: 5,
+            retryDelay: 5000
+          }
+        }),
+        inject: [ConfigService]
+      },
+      {
+        name: `JAVA_AFIS`,
+        imports: [ConfigModule],
+        useFactory: async (configService: ConfigService) => ({
+          transport: Transport.TCP,
+          options: {
+            host: configService.get<string>(`afis.host`) as string,
+            port: configService.get<number>(`afis.tcpPort`) as number,
+            retryAttempts: 5,
+            retryDelay: 5000
           }
         }),
         inject: [ConfigService]

+ 78 - 3
apps/fis-verification/src/fis-verification.service.ts

@@ -1,14 +1,89 @@
 import { Inject, Injectable } from '@nestjs/common';
 import { ClientProxy } from '@nestjs/microservices';
+import { interval } from 'rxjs';
+import * as net from 'net'
+import { ConfigService } from '@nestjs/config';
 
 @Injectable()
 export class FisVerificationService {
-  
-  constructor(@Inject(`SAMPLEAPP_SERVICE`) private client: ClientProxy) {
+
+  constructor(
+    @Inject(`SAMPLEAPP_SERVICE`) private sampleClient: ClientProxy,
+    @Inject(`JAVA_AFIS`) private javaClient: ClientProxy, // this one cannot work unfortunately
+    private configService: ConfigService
+  ) {
     // logic here
     setTimeout(() => {
-      this.client.emit(`message`, `Verification says HI`)
+      // logic here
     }, 5000)
+
+    interval(3000).subscribe(interval => {
+      this.sampleClient.emit(`message`, `Verification says HI`)
+      // this.javaClient.emit(`message`, `Testing Message  from Verification`)
+      // this.javaClient.send(`message`, `Testing Message  from Verification`)
+    })
+
+    this.tryThis()
+  }
+
+  tryThis() {
+    const port = this.configService.get<number>('afis.tcpPort')!;
+    const host = this.configService.get<string>('afis.host')!;
+    
+    const client = new net.Socket();
+  
+    const connectToServer = () => {
+      client.connect(port, host, () => {
+        console.log(`✅ Connected to Afis Java Server at ${host}:${port}`);
+      });
+    };
+  
+    // Attempt to connect initially
+    connectToServer();
+  
+    // Reconnect logic: try again after delay
+    client.on('error', (err) => {
+      console.error(`❌ TCP Error:`, err.message);
+      // Avoid crash on ECONNREFUSED etc.
+      setTimeout(connectToServer, 3000);
+    });
+  
+    client.on('close', (hadError) => {
+      console.warn(`⚠️ Connection closed${hadError ? ' due to error' : ''}. Reconnecting...`);
+      setTimeout(connectToServer, 3000);
+    });
+  
+    client.on('end', () => {
+      console.warn('⚠️ Server closed the connection.');
+    });
+  
+    // Optional: handle incoming data
+    client.on('data', (data) => {
+      console.log('📩 Received from server:', data.toString());
+    });
+  
+    // Message sending interval
+    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');
+    });
   }
   
 }
+
+/* Reason based on ChatGPT: Why ClientProxy.send() or emit() won't work 
+The NestJS ClientProxy (when configured for Transport.TCP) uses its own custom binary protocol under the hood. This includes:
+A message envelope that wraps your pattern and data.
+Message IDs and event headers.
+A specific serialization/deserialization logic that is not plain JSON.
+NO newline character at the end.
+So when your Java server, which expects a newline-terminated JSON message, receives this custom binary format, it gets confused or sees null.*/

+ 1 - 0
apps/fis-verification/src/main.ts

@@ -21,6 +21,7 @@ async function bootstrap() {
     }
   );
 
+  // await app.listen()
   await app.listen()
   console.log(`Verification microsservice is running on ${host}:${port}`);
 }

+ 4 - 1
apps/sample-app/src/sample-app.controller.ts

@@ -4,8 +4,11 @@ import { EventPattern } from '@nestjs/microservices';
 
 @Controller()
 export class SampleAppController {
-  constructor(private readonly sampleAppService: SampleAppService) { 
+  constructor(private readonly sampleAppService: SampleAppService) {
     // logic here
+    setTimeout(() => {
+      this.sampleAppService.talkToFingerprint(`hello`)
+    }, 5000)
   }
 
   @Get()

+ 4 - 0
config/configurations.ts

@@ -14,5 +14,9 @@ export default () => ({
     verification: {
         host: process.env.HOST,
         tcpPort: process.env.VERIFICATION_TCP_PORT
+    },
+    afis: {
+        host: process.env.HOST,
+        tcpPort: process.env.AFIS_TCP_PORT
     }
 });