Browse Source

update socket implementation

enzo 3 days ago
parent
commit
cb8e130ed4

+ 3 - 0
.vscode/settings.json

@@ -0,0 +1,3 @@
+{
+    "java.configuration.updateBuildConfiguration": "interactive"
+}

+ 1 - 1
apps/fis-verification/src/fis-verification.service.ts

@@ -18,7 +18,7 @@ export class FisVerificationService {
     }, 5000)
 
     interval(3000).subscribe(interval => {
-      this.sampleClient.emit(`message`, `Verification says HI`)
+      // this.sampleClient.emit(`message`, `Verification says HI`)
       // this.javaClient.emit(`message`, `Testing Message  from Verification`)
       // this.javaClient.send(`message`, `Testing Message  from Verification`)
     })

+ 11 - 1
apps/sample-app/src/main.ts

@@ -3,7 +3,9 @@ import { SampleAppModule } from './sample-app.module';
 import { MicroserviceOptions, Transport } from '@nestjs/microservices';
 import { ConfigService } from '@nestjs/config';
 import 'dotenv/config'
+import { Logger } from '@nestjs/common';
 
+const mainLogger = new Logger(`Sample-App`)
 async function bootstrap() {
   // This example contains a hybrid application (HTTP + TCP + Socket)
   const app = await NestFactory.create(SampleAppModule);
@@ -12,6 +14,14 @@ async function bootstrap() {
   const host: string = config.get<string>(`sampleApp.host`) as string
   const restPort: number = config.get<number>(`sampleApp.restPort`) as number
   const tcpPort: number = config.get<number>(`sampleApp.tcpPort`) as number
+  const socketPort: number = config.get<number>(`sampleApp.socketPort`) as number
+
+  app.enableCors({
+    origin: `*`, // specify the allowed origin(s)
+    methods: 'GET,POST,PUT,DELETE,OPTIONS',
+    allowedHeaders: 'Content-Type, Authorization',
+    credentials: true, // if you need to support cookies or other credentials
+  });
 
   app.connectMicroservice<MicroserviceOptions>({
     transport: Transport.TCP,
@@ -25,6 +35,6 @@ async function bootstrap() {
 
   await app.startAllMicroservices();
   await app.listen(restPort, host);
-  console.log(`REST API is running on: ${await app.getUrl()} and TCP is running on ${host}:${tcpPort}`);
+  console.log(`REST API is running on: ${await app.getUrl()} and TCP is running on ${host}:${tcpPort} and Socket is running on ${host}:${socketPort}`);
 }
 bootstrap();

+ 40 - 0
apps/sample-app/src/sample-app.gateway.ts

@@ -0,0 +1,40 @@
+import { ConnectedSocket, MessageBody, OnGatewayConnection, OnGatewayDisconnect, SubscribeMessage, WebSocketGateway, WebSocketServer, WsResponse, } from '@nestjs/websockets';
+import { from, Observable } from 'rxjs';
+import { map } from 'rxjs/operators';
+import { Server, Socket } from 'socket.io';
+
+@WebSocketGateway({
+    cors: {
+        origin: '*',
+    },
+    namespace: `Sample-App`
+})
+export class SampleEventsGateway implements OnGatewayConnection, OnGatewayDisconnect {
+    @WebSocketServer()
+    server: Server;
+
+    constructor() {
+        // logic here
+        // console.log(`Socket Server started??`)
+    }
+
+    @SubscribeMessage('test')
+    test(@MessageBody() data: any, @ConnectedSocket() client: Socket): Observable<WsResponse<any>> {
+        throw new Error(`Method not implemented`)
+    }
+
+    @SubscribeMessage('message')
+    handleMesage(@MessageBody() data: string, @ConnectedSocket() client: Socket): void {
+        console.log(data)
+        console.log(`${data} from ${client.id}`)
+    }
+
+    // this two methods are non essential. as they are used to keep track of the local ui port 3000, not keeping track of the actual clients 
+    handleConnection(client: any) {
+        console.log('Monitoring UI connected:', client.id);
+    }
+
+    handleDisconnect(client: any) {
+        console.log('Monitoring UI disconnected:', client.id);
+    }
+}

+ 2 - 1
apps/sample-app/src/sample-app.module.ts

@@ -2,7 +2,7 @@ import { Module } from '@nestjs/common';
 import { SampleAppController } from './sample-app.controller';
 import { SampleAppService } from './sample-app.service';
 import { ClientsModule, Transport } from '@nestjs/microservices';
-import { SampleEventsGateway } from './sample.gateway';
+import { SampleEventsGateway } from './sample-app.gateway';
 import { ConfigModule, ConfigService } from '@nestjs/config';
 import configuration from '../../../config/configurations';
 import 'dotenv/config'
@@ -52,5 +52,6 @@ import 'dotenv/config'
   ],
   controllers: [SampleAppController],
   providers: [SampleAppService, SampleEventsGateway],
+  exports: [SampleAppService]
 })
 export class SampleAppModule { }

+ 0 - 29
apps/sample-app/src/sample.gateway.ts

@@ -1,29 +0,0 @@
-import { ConnectedSocket, MessageBody, SubscribeMessage, WebSocketGateway, WebSocketServer, WsResponse, } from '@nestjs/websockets';
-import { from, Observable } from 'rxjs';
-import { map } from 'rxjs/operators';
-import { Server, Socket } from 'socket.io';
-
-@WebSocketGateway({
-    cors: {
-        origin: '*',
-    },
-    namespace: `Sample-App`
-})
-export class SampleEventsGateway {
-    @WebSocketServer()
-    server: Server;
-
-    constructor() {
-        // logic here
-    }
-
-    @SubscribeMessage('message')
-    handleMesage(@MessageBody() data: any, @ConnectedSocket() client: Socket): Observable<WsResponse<any>> {
-        throw new Error(`Method not implemented`)
-    }
-
-    @SubscribeMessage('test')
-    test(@MessageBody() data: string, @ConnectedSocket() client: Socket): void {
-        console.log(`${data} from ${client.id}`)
-    }
-}

+ 2 - 1
config/configurations.ts

@@ -5,7 +5,8 @@ export default () => ({
     sampleApp: {
         host: process.env.HOST,
         restPort: process.env.SAMPLEAPP_REST_PORT,
-        tcpPort: process.env.SAMPLEAPP_TCP_PORT
+        tcpPort: process.env.SAMPLEAPP_TCP_PORT,
+        socketPort: process.env.SAMPLEAPP_SOCKET_PORT,
     },
     fingerprint: {
         host: process.env.HOST,

+ 14 - 0
libs/java/README.md

@@ -0,0 +1,14 @@
+# Java Projects
+
+Java repo in  **VS Code**.
+
+## 🚀 Getting Started
+
+
+### 📌 Setup Instructions
+
+1. Clone the repository (if using GitHub):
+   ```sh
+   git clone <repo-url>
+   cd <your-project-folder>
+   maven install && build && compile

+ 71 - 0
package-lock.json

@@ -19,6 +19,7 @@
         "dotenv": "^16.4.7",
         "reflect-metadata": "^0.2.2",
         "rxjs": "^7.8.1",
+        "socket.io-client": "^4.8.1",
         "uuid": "^11.1.0"
       },
       "devDependencies": {
@@ -5484,6 +5485,36 @@
         "node": ">=10.2.0"
       }
     },
+    "node_modules/engine.io-client": {
+      "version": "6.6.3",
+      "resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-6.6.3.tgz",
+      "integrity": "sha512-T0iLjnyNWahNyv/lcjS2y4oE358tVS/SYQNxYXGAJ9/GLgH4VCvOQ/mhTjqU88mLZCQgiG8RIegFHYCdVC+j5w==",
+      "license": "MIT",
+      "dependencies": {
+        "@socket.io/component-emitter": "~3.1.0",
+        "debug": "~4.3.1",
+        "engine.io-parser": "~5.2.1",
+        "ws": "~8.17.1",
+        "xmlhttprequest-ssl": "~2.1.1"
+      }
+    },
+    "node_modules/engine.io-client/node_modules/debug": {
+      "version": "4.3.7",
+      "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz",
+      "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==",
+      "license": "MIT",
+      "dependencies": {
+        "ms": "^2.1.3"
+      },
+      "engines": {
+        "node": ">=6.0"
+      },
+      "peerDependenciesMeta": {
+        "supports-color": {
+          "optional": true
+        }
+      }
+    },
     "node_modules/engine.io-parser": {
       "version": "5.2.3",
       "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz",
@@ -9960,6 +9991,38 @@
         }
       }
     },
+    "node_modules/socket.io-client": {
+      "version": "4.8.1",
+      "resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.8.1.tgz",
+      "integrity": "sha512-hJVXfu3E28NmzGk8o1sHhN3om52tRvwYeidbj7xKy2eIIse5IoKX3USlS6Tqt3BHAtflLIkCQBkzVrEEfWUyYQ==",
+      "license": "MIT",
+      "dependencies": {
+        "@socket.io/component-emitter": "~3.1.0",
+        "debug": "~4.3.2",
+        "engine.io-client": "~6.6.1",
+        "socket.io-parser": "~4.2.4"
+      },
+      "engines": {
+        "node": ">=10.0.0"
+      }
+    },
+    "node_modules/socket.io-client/node_modules/debug": {
+      "version": "4.3.7",
+      "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz",
+      "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==",
+      "license": "MIT",
+      "dependencies": {
+        "ms": "^2.1.3"
+      },
+      "engines": {
+        "node": ">=6.0"
+      },
+      "peerDependenciesMeta": {
+        "supports-color": {
+          "optional": true
+        }
+      }
+    },
     "node_modules/socket.io-parser": {
       "version": "4.2.4",
       "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.4.tgz",
@@ -11632,6 +11695,14 @@
         }
       }
     },
+    "node_modules/xmlhttprequest-ssl": {
+      "version": "2.1.2",
+      "resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.1.2.tgz",
+      "integrity": "sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ==",
+      "engines": {
+        "node": ">=0.4.0"
+      }
+    },
     "node_modules/xtend": {
       "version": "4.0.2",
       "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",

+ 1 - 0
package.json

@@ -30,6 +30,7 @@
     "dotenv": "^16.4.7",
     "reflect-metadata": "^0.2.2",
     "rxjs": "^7.8.1",
+    "socket.io-client": "^4.8.1",
     "uuid": "^11.1.0"
   },
   "devDependencies": {

+ 1 - 1
startDev.bat

@@ -4,6 +4,6 @@ cd /d "%~dp0"
 
 echo Starting services DEV MODE...
 start wt -M -d "." cmd /k "nest start sample-app --watch" ; split-pane -d "." cmd /k "nest start fis-fingerprint --watch" ; split-pane -d "." cmd /k "nest start fis-verification --watch" 
-
+start cmd /k "cd libs/java/FingerprintDataVerification && mvn clean install && mvn compile exec:java"
 @REM to start with separate terminal windows
 @REM start wt -M -d "." cmd /k "nest start fis-verification --watch"

+ 5 - 0
terminate.bat

@@ -5,6 +5,11 @@ for /f "tokens=2" %%a in ('tasklist ^| findstr /i /c:"node.exe" /c:"BUILD_PROCES
   taskkill /F /PID %%a
 )
 
+REM Kill all java.exe processes except for the one associated with your build script
+for /f "tokens=2" %%a in ('tasklist ^| findstr /i /c:"java.exe" /c:"BUILD_PROCESS=yes"') do (
+  taskkill /F /PID %%a
+)
+
 REM Close the terminal window (Windows Terminal)
 taskkill /F /IM WindowsTerminal.exe
 

+ 25 - 0
test/socket-io.js

@@ -0,0 +1,25 @@
+const io = require('socket.io-client');
+
+// Connect to the Socket.IO server
+// const socket = io('http://127.0.0.1:3000');
+const socket = io('http://127.0.0.1:3000/Sample-App');
+
+// Listen for the 'connect' event
+socket.on('connect', () => {
+  console.log('Connected to the server!');
+  
+  // Emit a test event to the server
+  setTimeout(() => {
+      socket.emit('message', { message: 'Hello from the client!' });
+  }, 3000)
+});
+
+// Listen for a 'test-response' event from the server
+socket.on('message', (data) => {
+  console.log('Received from server:', data);
+});
+
+// Listen for the 'disconnect' event
+socket.on('disconnect', () => {
+  console.log('Disconnected from the server');
+});