|
@@ -0,0 +1,58 @@
|
|
|
+import { Observable, Subject } from "rxjs";
|
|
|
+import { io, Socket, Socket as SocketClient } from "socket.io-client";
|
|
|
+import { Socket as SocketServer } from "socket.io"
|
|
|
+import { startClientSocketConnection, startSocketServer } from "../utils/socket.utils";
|
|
|
+import { TransportInterface, TransportSettings } from "../interface/transport.interface";
|
|
|
+
|
|
|
+export class WebsocketTransport implements TransportInterface {
|
|
|
+ private websocketRole!: 'Server' | 'Client' | null
|
|
|
+ private clientSocket!: SocketClient
|
|
|
+ private serverSocket!: SocketServer
|
|
|
+ private responseSubject: Subject<any> = new Subject()
|
|
|
+ private eventNotification: Subject<any> = new Subject()
|
|
|
+
|
|
|
+ constructor(setting: TransportSettings) {
|
|
|
+ this.websocketRole == setting.role
|
|
|
+ if (setting.role == 'Server') {
|
|
|
+ startSocketServer(setting.profileInfo.port as number).then((server: SocketServer) => {
|
|
|
+ this.serverSocket = server
|
|
|
+ })
|
|
|
+ }
|
|
|
+ if (setting.role == 'Client') {
|
|
|
+ startClientSocketConnection(setting.profileInfo.url as string).then((client: Socket) => {
|
|
|
+ this.clientSocket = client
|
|
|
+ })
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ send(message: any): Observable<any> {
|
|
|
+ return new Observable((response) => {
|
|
|
+ if (this.websocketRole == 'Server') {
|
|
|
+
|
|
|
+ }
|
|
|
+ if (this.websocketRole == 'Client') {
|
|
|
+ // filter message
|
|
|
+ this.clientSocket.emit('message', message)
|
|
|
+ this.responseSubject.subscribe(responseMsg => {
|
|
|
+ if (responseMsg.id == message.id && !responseMsg.complete) {
|
|
|
+ response.next(responseMsg)
|
|
|
+ }
|
|
|
+ if (responseMsg.id == message.id && responseMsg.complete) {
|
|
|
+ response.complete()
|
|
|
+ }
|
|
|
+ })
|
|
|
+ }
|
|
|
+ })
|
|
|
+ }
|
|
|
+
|
|
|
+ emit(message: any): void {
|
|
|
+ if (this.clientSocket) {
|
|
|
+ this.clientSocket.emit(`event`, message)
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ getTransportEventNotification(): Observable<any> {
|
|
|
+ return this.eventNotification as Observable<any>
|
|
|
+ }
|
|
|
+
|
|
|
+}
|