websocket.ts 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { Observable, Subject } from "rxjs";
  2. import { Socket as ClientSocket } from "socket.io-client";
  3. import { Socket as SocketForConnectedClient } from "socket.io"
  4. import { handleClientSocketConnection, handleNewSocketClient, startClientSocketConnection, startSocketServer, writeFile } from "../utils/socket.utils";
  5. import { ITransportReceiving, ITransportTransmitting, ReceiverProfile, TransmitterProfile, TransportEventNotification, TransportMessage, TransportSettings } from "../interface/ITransport.interface";
  6. /* Just code in the context that this websocket service will be handling multiple UI clients. Can think about the server communication at a later time. */
  7. export class WebsocketTransportService implements ITransportTransmitting, ITransportReceiving {
  8. private socketReceiverProfile: ReceiverProfile[] = []
  9. private incomingMessage: Subject<TransportMessage> = new Subject() // this is only for client roles only atm
  10. private eventNotification: Subject<TransportEventNotification> = new Subject()
  11. constructor(setting: TransportSettings) {
  12. if (setting.profileInfo.port) {
  13. startSocketServer(setting.profileInfo.port as number).subscribe({
  14. next: (connectedClient: SocketForConnectedClient) => {
  15. handleNewSocketClient(connectedClient, this.eventNotification, this.socketReceiverProfile)
  16. },
  17. error: error => console.error(error),
  18. })
  19. }
  20. // this is for those who wants to act as receiver. Usually for web browser, but servers can use this too.
  21. if (setting.profileInfo.url) {
  22. startClientSocketConnection(setting.profileInfo.url).then((socket: ClientSocket) => {
  23. handleClientSocketConnection(socket, this.incomingMessage).subscribe(this.eventNotification)
  24. }).catch((error) => {
  25. console.error(`WebsocketTransport ERROR:`, error)
  26. })
  27. }
  28. }
  29. // for transmission(Server Only, not applicable for client Socket)
  30. public async transmit(message: TransportMessage): Promise<string> {
  31. return new Promise((resolve, reject) => {
  32. let receiverInstance = this.socketReceiverProfile.find(obj => obj.uuid === message.receiverID);
  33. if (receiverInstance) {
  34. (receiverInstance?.instance as SocketForConnectedClient).emit(message.event, message.payload)
  35. resolve('Message called for delivery...')
  36. } else {
  37. reject(`Receiver cannot be found or doesn't exist...`)
  38. }
  39. })
  40. }
  41. public getTransportEventNotification(): Observable<TransportEventNotification> {
  42. return this.eventNotification as Observable<TransportEventNotification>
  43. }
  44. // for client UI eg
  45. public receive(): Observable<TransportMessage> {
  46. return this.incomingMessage.asObservable()
  47. }
  48. }