publisher.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { Subject } from 'rxjs';
  2. import * as WebSocket from 'ws';
  3. import { DataPrepService } from '../services/dataprep.service';
  4. import { StorageLocation } from '../types/interface';
  5. let msgData = new DataPrepService()
  6. /* ---------------------- COMPLEX OPERATION ------------------------------ */
  7. const msgPayload: Subject<any> = new Subject();
  8. let mongoStorage: StorageLocation = {
  9. type: `MongoDB`,
  10. url: `mongodb://192.168.100.59:27017/default`
  11. }
  12. msgData.loadObsData(mongoStorage, msgPayload)
  13. // Create a WebSocket server
  14. const wss = new WebSocket.Server({ port: 8080 });
  15. // Listen for connections to the WebSocket server
  16. wss.on('connection', (ws: WebSocket) => {
  17. console.log('Client connected');
  18. // Subscribe to the subject when a client connects
  19. const subscription = msgPayload.subscribe((element) => {
  20. const used = process.memoryUsage().heapUsed / 1024 / 1024;
  21. const total = process.memoryUsage().heapTotal / 1024 / 1024;
  22. console.log(`Heap memory usage: ${used.toFixed(2)} MB`);
  23. console.log(`Total heap size: ${total.toFixed(2)} MB`);
  24. console.log(`Emitting value ${element.appData.msgId} to client`);
  25. const messageString = JSON.stringify(element);
  26. ws.send(messageString);
  27. });
  28. // Listen for messages from the client
  29. ws.on('message', (message: any) => {
  30. console.log(`Received message from client: ${message}`);
  31. });
  32. // Unsubscribe from the subject when the client disconnects
  33. ws.on('close', () => {
  34. console.log('Client disconnected');
  35. subscription.unsubscribe();
  36. });
  37. });