socket.utils.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. import { Observable, Observer, Subject } from 'rxjs';
  2. import { createServer } from 'http';
  3. import { Server, Socket as SocketForConnectedClient } from 'socket.io';
  4. import { io, Socket as ClientSocket } from 'socket.io-client';
  5. import * as fs from 'fs'
  6. import { ReceiverProfile, TransportEventNotification, TransportMessage } from '../interface/ITransport.interface';
  7. import { v4 as uuidv4 } from 'uuid'
  8. export function startSocketServer(port: number): Observable<SocketForConnectedClient> {
  9. return new Observable((observer) => {
  10. try {
  11. let httpServer = createServer();
  12. let socketServer = new Server(httpServer)
  13. // something wrong here
  14. socketServer.on('connection', (socket) => {
  15. observer.next(socket)
  16. })
  17. socketServer.engine.on("connection_error", (err) => {
  18. console.log(err.req); // the request object
  19. console.log(err.code); // the error code, for example 1
  20. console.log(err.message); // the error message, for example "Session ID unknown"
  21. console.log(err.context); // some additional error context
  22. });
  23. // Start the socketServer
  24. httpServer.listen(port)
  25. } catch (error) {
  26. observer.error(error)
  27. }
  28. })
  29. }
  30. export async function startClientSocketConnection(serverUrl: string): Promise<ClientSocket> {
  31. return new Promise((resolve, reject) => {
  32. try {
  33. let clientSocket = io(serverUrl)
  34. // let clientSocket = io(serverUrl, {
  35. // reconnection: true, // Enable automatic reconnections
  36. // reconnectionAttempts: 100, // Retry up to 10 times
  37. // reconnectionDelay: 500, // Start with a 500ms delay
  38. // reconnectionDelayMax: 10000, // Delay can grow to a max of 10 seconds
  39. // randomizationFactor: 0.3,
  40. // })
  41. // Listen for a connection event
  42. clientSocket.on('connect', () => {
  43. console.log('Connected to the server:', clientSocket.id)
  44. resolve(clientSocket)
  45. });
  46. }
  47. catch (error) {
  48. reject(error)
  49. }
  50. })
  51. }
  52. // Specifically to write receiver profile information
  53. export async function writeFile(data: ReceiverProfile, filename: string): Promise<boolean> {
  54. return new Promise((resolve, reject) => {
  55. // Write JSON data to a file
  56. fs.writeFile(`${filename}.json`, JSON.stringify(data, null, 2), (err) => {
  57. if (err) {
  58. console.error('Error writing file', err);
  59. reject(false)
  60. } else {
  61. console.log('File has been written');
  62. resolve(true)
  63. }
  64. });
  65. })
  66. }
  67. // After establishing connection to the server, set up the credentials, confirm whether or not if there's any credentials, if not ask for one from the server
  68. export function handleClientSocketConnection(socket: ClientSocket, incomingMessage: Subject<TransportMessage>): Observable<TransportEventNotification> {
  69. return new Observable((eventNotification: Observer<TransportEventNotification>) => {
  70. let buffer: any[] = []
  71. let receiverProfileInfo!: ReceiverProfile
  72. checkOwnClientInfo('client1').then((profile: ReceiverProfile) => {
  73. receiverProfileInfo = profile
  74. socket.emit('profile', {
  75. name: 'Old Client',
  76. data: profile
  77. })
  78. }).catch((error) => {
  79. socket.emit('profile', {
  80. name: 'New Client',
  81. data: null
  82. })
  83. })
  84. // Listen for messages from the server. Generally here's the responses
  85. socket.on('message', (msg: any) => {
  86. console.log(`Websocket Client Transport Receieve Msg`, msg.id)
  87. if (receiverProfileInfo) {
  88. eventNotification.next({
  89. event: 'New Message',
  90. description: 'Received new message',
  91. transportType: 'WEBSOCKET',
  92. data: msg
  93. })
  94. incomingMessage.next({
  95. id: msg.header.MessageID,
  96. receiverID: receiverProfileInfo.uuid,
  97. payload: msg,
  98. event: 'New Message'
  99. })
  100. } else {
  101. // Do nothing. just store in local array first. Cannot process without information. but then again, don['t need information if acting as client
  102. // but for consistency sake, will impose the standard
  103. buffer.push(msg) // store locally for now
  104. }
  105. })
  106. socket.on('profile', (data: { name: string, message: any }) => {
  107. // console.log(data)
  108. if (data.name == 'New Profile') {
  109. console.log(`Assigned client Name: ${(data.message as ReceiverProfile).name}`)
  110. receiverProfileInfo = data.message as ReceiverProfile
  111. writeFile(data.message as ReceiverProfile, (data.message as ReceiverProfile).name).then(() => [
  112. // broadcast event to allow retransmission to release buffer
  113. eventNotification.next({
  114. event: 'Connection',
  115. description: 'Profile acquired || updated and stored',
  116. transportType: 'WEBSOCKET',
  117. })
  118. ]).catch((error) => { }) // do nothing at the moment.
  119. }
  120. if (data.name == 'Adjusted Profile') {
  121. console.log(`Assigned client Name: ${(data.message as ReceiverProfile).name}`)
  122. receiverProfileInfo = data.message as ReceiverProfile
  123. writeFile(data.message as ReceiverProfile, (data.message as ReceiverProfile).name).then(() => [
  124. // broadcast event to allow retransmission to release buffer
  125. eventNotification.next({
  126. event: 'Connection',
  127. description: 'Profile acquired || updated and stored',
  128. transportType: 'WEBSOCKET',
  129. })
  130. ]).catch((error) => { }) // do nothing at the moment.
  131. }
  132. if (data.name == 'Error') {
  133. console.log(`Server cannot find credentials`, data.message)
  134. // logic to request for new credentials
  135. }
  136. })
  137. // Handle disconnection
  138. socket.on('disconnect', () => {
  139. console.log('Websocket Client disconnected from the server');
  140. if (receiverProfileInfo) {
  141. eventNotification.next({
  142. event: 'Disconnection',
  143. description: 'Disconnected from the server',
  144. transportType: 'WEBSOCKET'
  145. })
  146. }
  147. });
  148. })
  149. }
  150. // Check if filename exists. Return profile information if there's any
  151. export async function checkOwnClientInfo(filename: string): Promise<ReceiverProfile> {
  152. return new Promise((resolve, reject) => {
  153. // Check if the file exists
  154. if (fs.existsSync(`${filename}.json`)) {
  155. try {
  156. // Read the file contents
  157. const fileData = fs.readFileSync(`${filename}.json`, 'utf8');
  158. // If the file is empty, return an error
  159. if (fileData.trim() === "") {
  160. throw new Error("File is empty");
  161. }
  162. // Parse and return the data if present
  163. const jsonData = JSON.parse(fileData);
  164. resolve(jsonData)
  165. } catch (err) {
  166. // Handle parsing errors or other file-related errors
  167. console.error("Error reading or parsing file:", err);
  168. reject('');
  169. }
  170. } else {
  171. console.error("File does not exist");
  172. reject('');
  173. }
  174. })
  175. }
  176. // For SERVER Usage: set up socket listeners to start listening for different events
  177. export function handleNewSocketClient(socket: SocketForConnectedClient, eventNotification: Subject<TransportEventNotification>, socketReceiverProfile: ReceiverProfile[]): void {
  178. console.log(`Setting up listeners for socket:${socket.id}`)
  179. // returns the socket client instance
  180. // listen to receiver's initiotion first before assigning 'credentials'
  181. socket.on(`profile`, (message: { name: string, data: ReceiverProfile }) => {
  182. if (message.name == 'New Client') {
  183. let receiverProfile: ReceiverProfile = {
  184. uuid: uuidv4(),
  185. name: `Client${uuidv4()}`,
  186. dateCreated: new Date(),
  187. transportType: `WEBSOCKET`,
  188. eventNotification: new Subject(),
  189. instance: socket
  190. }
  191. // publish first event notification
  192. eventNotification.next({
  193. event: 'Connection',
  194. description: 'New Client Connected',
  195. transportType: 'WEBSOCKET',
  196. data: {
  197. receiverID: receiverProfile.uuid,
  198. receiverName: receiverProfile.name,
  199. date: new Date(),
  200. payload: receiverProfile
  201. }
  202. })
  203. // send to receiver for reference
  204. socket.emit('profile', {
  205. name: `New Profile`, message: {
  206. uuid: receiverProfile.uuid,
  207. name: receiverProfile.name,
  208. dateCreated: receiverProfile.dateCreated,
  209. transportType: `WEBSOCKET`,
  210. eventNotification: null,
  211. instance: null // have to put null, otherwise circular reference maximum stack error
  212. }
  213. })
  214. socketReceiverProfile.push(receiverProfile)
  215. startListening(socket, receiverProfile)
  216. } else {
  217. // update first
  218. let receiverProfile: ReceiverProfile | undefined = socketReceiverProfile.find(obj => obj.uuid === message.data.uuid)
  219. if (receiverProfile) {
  220. receiverProfile.instance = socket
  221. socket.emit('profile', { name: 'Adjusted Profile', message: receiverProfile })
  222. // need to start listening again, because it's assigned a different socket instance this time round
  223. startListening(socket, receiverProfile)
  224. } else {
  225. socket.emit('profile', { name: 'Error', message: 'Receiver Profile Not found' })
  226. }
  227. }
  228. })
  229. }
  230. export function startListening(socket: SocketForConnectedClient, receiverProfile: ReceiverProfile): void {
  231. /* Generally, we don't need this unless in the case of being the receiver */
  232. socket.on('message', (message: any) => {
  233. // here
  234. })
  235. socket.on('request', (request: any) => {
  236. // here : Let's say there's a subcsription request here
  237. receiverProfile.eventNotification.next({
  238. event: 'New Message',
  239. description: 'Incoming request',
  240. transportType: 'WEBSOCKET',
  241. data: {
  242. receiverID: receiverProfile.uuid,
  243. receiverName: receiverProfile.name,
  244. date: new Date(),
  245. payload: request
  246. }
  247. })
  248. })
  249. socket.on('notification', (notification: any) => {
  250. // logic here
  251. })
  252. socket.on('disconnect', () => {
  253. receiverProfile.eventNotification.next(
  254. {
  255. event: 'Disconnection',
  256. description: `Existing Client ${socket.id} disonnected`,
  257. transportType: `WEBSOCKET`,
  258. data: {
  259. receiverID: receiverProfile.uuid,
  260. receiverName: receiverProfile.name,
  261. date: new Date(),
  262. }
  263. }
  264. )
  265. })
  266. }