socket-client.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. import { Observable, Subject, takeWhile } from "rxjs";
  2. import { prepareResponseMessages } from "../../services/utility/prepareFISmessage";
  3. import { BaseMessage } from "../../dependencies/logging/interface/export";
  4. import { io, Socket } from "socket.io-client";
  5. import { WrappedMessage } from "../../interfaces/general.interface";
  6. import * as fs from 'fs'
  7. import { ClientInfo } from "./socket.service";
  8. import { MongoService } from "./temp-log-service";
  9. let onHoldMessagesSubject: Subject<WrappedMessage> = new Subject()
  10. let toBePassedOverToApp: Subject<BaseMessage> = new Subject()
  11. // Serve static files (optional)
  12. let sender: Subject<BaseMessage> = prepareResponseMessages(5, 1000)
  13. let serverSocketUrl: string = 'http://192.168.100.96:3000'
  14. let socket: Socket
  15. let client: string = 'client2'
  16. let mongoService: MongoService = new MongoService(client)
  17. establishSocketConnection(serverSocketUrl).then(() => {
  18. // sender.subscribe({
  19. // next: (message: BaseMessage) => {
  20. // makeRequest(message).subscribe({
  21. // next: (message: BaseMessage) => {
  22. // },
  23. // complete: () => console.log(`Request ${message.header.messageID} has acquired all responses.`)
  24. // })
  25. // }
  26. // })
  27. })
  28. // the interface the client Program will make without having to decide transport protocol
  29. function makeRequest(request: BaseMessage): Observable<BaseMessage> {
  30. return new Observable((response) => {
  31. sendMessage(request)
  32. toBePassedOverToApp.subscribe({
  33. next: (message: BaseMessage) => {
  34. // console.log(message.header.messageName)
  35. // The identification of responses mapping to the request be adjusted accordingly
  36. // For now it's a simple demulti-plexing
  37. if (message.header.messageID == request.header.messageID && message.header.messageName != 'Complete') {
  38. response.next(message)
  39. }
  40. if (message.header.messageID == request.header.messageID && message.header.messageName == 'Complete') {
  41. response.complete()
  42. }
  43. },
  44. error: err => console.error(err),
  45. complete: () => { }
  46. })
  47. })
  48. }
  49. // socket util: Assuming that the client program would already have something like this in place
  50. async function establishSocketConnection(serverUrl: string): Promise<any> {
  51. return new Promise((resolve, reject) => {
  52. try {
  53. socket = io(serverUrl, {
  54. reconnection: true, // Enable automatic reconnections
  55. reconnectionAttempts: 100, // Retry up to 10 times
  56. reconnectionDelay: 500, // Start with a 500ms delay
  57. reconnectionDelayMax: 10000, // Delay can grow to a max of 10 seconds
  58. randomizationFactor: 0.3,
  59. })
  60. // Check if it's a previuos client.
  61. let data: ClientInfo | null = checkOwnClientInfo(client)
  62. if (data) {
  63. socket.emit('notification', { agenda: 'existingClient', data: data })
  64. } else {
  65. socket.emit('notification', { agenda: 'newClient' })
  66. }
  67. // Listen for a connection event
  68. socket.on('connect', () => {
  69. // socket.emit('Hello from the client!')
  70. console.log('Connected to the server:', socket.id)
  71. });
  72. // Listen for messages from the server
  73. socket.on('response', (msg: WrappedMessage) => {
  74. console.log('Message from server:', msg.payload.header.messageName, ' for ', msg.payload.header.messageID);
  75. mongoService.write(msg.payload, msg.payload.header.messageID, () => console.log(`Error function doesn't exist.`))
  76. // Check the sequence by ensuring the message value before the current message exists, then pass them over to "App"
  77. // onHoldMessagesSubject.next(msg)
  78. // checkMessage(msg).then(() => [
  79. // toBePassedOverToApp.next(msg.payload as BaseMessage)
  80. // ]).catch((err) => console.error(err))
  81. toBePassedOverToApp.next(msg.payload as BaseMessage)
  82. })
  83. socket.on('notification', (msg: any) => {
  84. if (msg.notification == 'Your credentials') {
  85. console.log(`Assigned client Name: ${msg.socketInfo.clientName}`)
  86. writeFile(msg.socketInfo as ClientInfo, client)
  87. }
  88. if (msg.notification == 'Your updated credentials') {
  89. console.log(`Updated socket ID: `, msg)
  90. // writeFile(msg.socketInfo as ClientInfo)
  91. }
  92. if (msg.notification == 'Failed Request') {
  93. console.log(`Resending request...`, msg.data.header.messageID)
  94. setTimeout(() => {
  95. sender.next(msg.data)
  96. }, 1000)
  97. }
  98. })
  99. resolve('')
  100. // Handle disconnection
  101. socket.on('disconnect', () => {
  102. console.log('Disconnected from the server');
  103. // receiverConnectionState.next('OFFLINE')
  104. });
  105. }
  106. catch (error) {
  107. reject(error)
  108. }
  109. })
  110. }
  111. function checkOwnClientInfo(filename: string): ClientInfo | null {
  112. // Check if the file exists
  113. if (fs.existsSync(`${filename}.json`)) {
  114. try {
  115. // Read the file contents
  116. const fileData = fs.readFileSync(`${filename}.json`, 'utf8');
  117. // If the file is empty, return an error
  118. if (fileData.trim() === "") {
  119. throw new Error("File is empty");
  120. }
  121. // Parse and return the data if present
  122. const jsonData = JSON.parse(fileData);
  123. return jsonData;
  124. } catch (err) {
  125. // Handle parsing errors or other file-related errors
  126. console.error("Error reading or parsing file:", err.message);
  127. return null;
  128. }
  129. } else {
  130. console.error("File does not exist");
  131. return null;
  132. }
  133. }
  134. function writeFile(data: ClientInfo, filename: string) {
  135. // Write JSON data to a file
  136. fs.writeFile(`${filename}.json`, JSON.stringify(data, null, 2), (err) => {
  137. if (err) {
  138. console.error('Error writing file', err);
  139. } else {
  140. console.log('File has been written');
  141. }
  142. });
  143. }
  144. async function sendMessage(message: BaseMessage): Promise<any> {
  145. return new Promise((resolve, reject) => {
  146. try {
  147. // extra precaution: According to chatgpt, if disconnected, then the payload will be loaded back in event queue whilst the socket will try to reestablish connection
  148. // https://socket.io/docs/v4/client-offline-behavior/
  149. socket.emit('request', message); // inherently an aysnc
  150. console.log(`SocketEmit() for message to event queue ${message.header.messageID}`)
  151. resolve('')
  152. } catch (error) {
  153. console.error('Error emitting message:', error);
  154. sender.next(message)
  155. reject(error)
  156. }
  157. })
  158. }
  159. // SO concept will be that if the message behind it is received, then
  160. async function checkMessage(message: WrappedMessage): Promise<any> {
  161. return new Promise((resolve, reject) => {
  162. if (message.previousMessageID) {
  163. onHoldMessagesSubject.pipe(
  164. takeWhile(item => message.previousMessageID === item.thisMessageID)
  165. ).subscribe({
  166. complete: () => {
  167. resolve('previousMessageID matched')
  168. // console.log(`${message.payload.header.messageID} : Previous messageID(${message.previousMessageID}) matched`)
  169. // console.log(`matched`)
  170. }
  171. })
  172. } else {
  173. console.log('No previous messageID. This should be the first message')
  174. resolve('No previous message ID. Please Proceed.')
  175. }
  176. })
  177. }