|
@@ -1,11 +1,11 @@
|
|
|
import { BehaviorSubject, Observable, Observer, Subject } from 'rxjs';
|
|
|
import { createServer } from 'http';
|
|
|
import { Server, Socket as SocketForConnectedClient } from 'socket.io';
|
|
|
-import { io, Socket as ClientSocket } from 'socket.io-client';
|
|
|
+import { io, Socket as SocketForConnectedServer } from 'socket.io-client';
|
|
|
import * as fs from 'fs'
|
|
|
import { v4 as uuidv4 } from 'uuid'
|
|
|
import { ConnectionState, Transport, TransportEvent, TransportMessage } from '../interface/connector.interface';
|
|
|
-import { ConnectedClientSocket, ConnectedServerSocket } from '../transport/websocket';
|
|
|
+import { ConnectedSocketClient, ConnectedSocketServer } from '../transport/websocket';
|
|
|
import { EventMessage } from '../interface/transport.interface';
|
|
|
import ConsoleLogger from './log.utils';
|
|
|
const console: ConsoleLogger = new ConsoleLogger(`SocketUtils`, ['transport'])
|
|
@@ -39,11 +39,11 @@ export function startSocketServer(port: number): Observable<SocketForConnectedCl
|
|
|
})
|
|
|
}
|
|
|
|
|
|
-export async function startClientSocketConnection(serverUrl: string): Promise<ClientSocket> {
|
|
|
+export async function startClientSocketConnection(serverUrl: string): Promise<SocketForConnectedServer> {
|
|
|
return new Promise((resolve, reject) => {
|
|
|
try {
|
|
|
// let clientSocket = io(serverUrl)
|
|
|
- let clientSocket: ClientSocket = io(serverUrl, {
|
|
|
+ let clientSocket: SocketForConnectedServer = io(serverUrl, {
|
|
|
reconnection: true, // Enable automatic reconnections
|
|
|
reconnectionAttempts: 1000, // Retry up to 10 times
|
|
|
reconnectionDelay: 500, // Start with a 500ms delay
|
|
@@ -59,10 +59,10 @@ export async function startClientSocketConnection(serverUrl: string): Promise<Cl
|
|
|
}
|
|
|
|
|
|
// 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
|
|
|
-export function handleClientSocketConnection(socket: ClientSocket, serversConnected: ConnectedServerSocket[]): Observable<TransportEvent> {
|
|
|
+export function handleClientSocketConnection(socket: SocketForConnectedServer, serversConnected: ConnectedSocketServer[]): Observable<TransportEvent> {
|
|
|
return new Observable((eventNotification: Observer<TransportEvent>) => {
|
|
|
let buffer: any[] = []
|
|
|
- let receiverProfileInfo!: ConnectedServerSocket
|
|
|
+ let receiverProfileInfo!: ConnectedSocketServer
|
|
|
|
|
|
// Listen for a connection event
|
|
|
socket.on('connect', () => {
|
|
@@ -120,14 +120,14 @@ export function handleClientSocketConnection(socket: ClientSocket, serversConnec
|
|
|
socketInstance: socket,
|
|
|
connectionState: new BehaviorSubject<ConnectionState>(`ONLINE`)
|
|
|
}
|
|
|
- writeFile(data.message as ConnectedServerSocket, (data.message as ConnectedServerSocket).id).then(() => {
|
|
|
+ writeFile(data.message as ConnectedSocketServer, (data.message as ConnectedSocketServer).id).then(() => {
|
|
|
// broadcast event to allow transmission manager to instantiate transmission components
|
|
|
eventNotification.next({
|
|
|
id: uuidv4(),
|
|
|
event: `New Server`,
|
|
|
data: {
|
|
|
- clientId: (data.message as ConnectedServerSocket).id,
|
|
|
- message: `New Websocket Channel ${(data.message as ConnectedServerSocket).id} established.`
|
|
|
+ clientId: (data.message as ConnectedSocketServer).id,
|
|
|
+ message: `New Websocket Channel ${(data.message as ConnectedSocketServer).id} established.`
|
|
|
} as EventMessage
|
|
|
})
|
|
|
// broadcast event to allow retransmission to relase buffered messages
|
|
@@ -135,17 +135,17 @@ export function handleClientSocketConnection(socket: ClientSocket, serversConnec
|
|
|
id: uuidv4(),
|
|
|
event: `Server Connected`,
|
|
|
data: {
|
|
|
- clientId: (data.message as ConnectedServerSocket).id,
|
|
|
- message: `Server ${(data.message as ConnectedServerSocket).id} connected and ready to go.`
|
|
|
+ clientId: (data.message as ConnectedSocketServer).id,
|
|
|
+ message: `Server ${(data.message as ConnectedSocketServer).id} connected and ready to go.`
|
|
|
} as EventMessage
|
|
|
})
|
|
|
}).catch((error) => { }) // do nothing at the moment.
|
|
|
serversConnected.push(receiverProfileInfo)
|
|
|
}
|
|
|
if (data.name == 'Adjusted Profile') {
|
|
|
- console.log({ message: `Adjusted client Name: ${(data.message as ConnectedServerSocket).id}` })
|
|
|
+ console.log({ message: `Adjusted client Name: ${(data.message as ConnectedSocketServer).id}` })
|
|
|
// Update websocket instance record
|
|
|
- let clientObj: ConnectedServerSocket | undefined = serversConnected.find(obj => obj.id === data.message.id)
|
|
|
+ let clientObj: ConnectedSocketServer | undefined = serversConnected.find(obj => obj.id === data.message.id)
|
|
|
if (clientObj) {
|
|
|
receiverProfileInfo.id = (data.message.id)
|
|
|
|
|
@@ -156,14 +156,14 @@ export function handleClientSocketConnection(socket: ClientSocket, serversConnec
|
|
|
message: `Just to make sure they are pointed accurately: This should be ONLINE: ${receiverProfileInfo.connectionState.getValue()} !! Id match? ${receiverProfileInfo.id == clientObj.id ? true : false}`,
|
|
|
})
|
|
|
}
|
|
|
- writeFile(data.message as ConnectedServerSocket, (data.message as ConnectedServerSocket).id).then(() => {
|
|
|
+ writeFile(data.message as ConnectedSocketServer, (data.message as ConnectedSocketServer).id).then(() => {
|
|
|
// broadcast event to allow retransmission to release buffer
|
|
|
eventNotification.next({
|
|
|
id: uuidv4(),
|
|
|
event: 'Server Connected',
|
|
|
data: {
|
|
|
- clientId: (data.message as ConnectedServerSocket).id,
|
|
|
- message: `Existing Websocket Channel ${(data.message as ConnectedServerSocket).id} re-established.`
|
|
|
+ clientId: (data.message as ConnectedSocketServer).id,
|
|
|
+ message: `Existing Websocket Channel ${(data.message as ConnectedSocketServer).id} re-established.`
|
|
|
} as EventMessage
|
|
|
})
|
|
|
}).catch((error) => { }) // do nothing at the moment.
|
|
@@ -199,14 +199,14 @@ export function handleClientSocketConnection(socket: ClientSocket, serversConnec
|
|
|
}
|
|
|
|
|
|
// For SERVER Usage: set up socket listeners to start listening for different events
|
|
|
-export function handleNewSocketClient(socket: SocketForConnectedClient, connectedClientSocket: ConnectedClientSocket[]): Observable<TransportEvent> {
|
|
|
+export function handleNewSocketClient(socket: SocketForConnectedClient, connectedClientSocket: ConnectedSocketClient[]): Observable<TransportEvent> {
|
|
|
return new Observable((event: Observer<TransportEvent>) => {
|
|
|
console.log({ message: `Setting up listeners for socket:${socket.id}` })
|
|
|
// returns the socket client instance
|
|
|
// listen to receiver's initiotion first before assigning 'credentials'
|
|
|
socket.on(`profile`, (message: { name: string, data: any }) => {
|
|
|
if (message.name == 'New Client') {
|
|
|
- let clientInstance: ConnectedClientSocket = {
|
|
|
+ let clientInstance: ConnectedSocketClient = {
|
|
|
id: uuidv4(), // client should only be assigned at this level. And is passed around for reference pointing
|
|
|
dateCreated: new Date(),
|
|
|
socketInstance: socket,
|
|
@@ -232,20 +232,20 @@ export function handleNewSocketClient(socket: SocketForConnectedClient, connecte
|
|
|
startListening(socket, clientInstance, event)
|
|
|
} else {
|
|
|
// update first
|
|
|
- let clientInstance: ConnectedClientSocket | undefined
|
|
|
+ let clientInstance: ConnectedSocketClient | undefined
|
|
|
if (connectedClientSocket.length > 0) {
|
|
|
clientInstance = connectedClientSocket.find(obj => obj.id === message.data.id)
|
|
|
handleFoundClient(clientInstance)
|
|
|
} else {
|
|
|
// for the case server itself got shit down or something
|
|
|
- checkIfClientExists(message.data.id).then((client: ConnectedClientSocket) => {
|
|
|
+ checkIfClientExists(message.data.id).then((client: ConnectedSocketClient) => {
|
|
|
clientInstance = client
|
|
|
handleFoundClient(clientInstance)
|
|
|
}).catch(error => {
|
|
|
console.log({ message: `Promise Error`, details: error })
|
|
|
})
|
|
|
}
|
|
|
- function handleFoundClient(clientInstance: ConnectedClientSocket | undefined) {
|
|
|
+ function handleFoundClient(clientInstance: ConnectedSocketClient | undefined) {
|
|
|
if (clientInstance) {
|
|
|
console.log({ message: `Socket Client ${clientInstance.id} Found` })
|
|
|
socket.emit('profile', { name: 'Adjusted Profile', message: { id: clientInstance.id } })
|
|
@@ -266,7 +266,7 @@ export function handleNewSocketClient(socket: SocketForConnectedClient, connecte
|
|
|
|
|
|
|
|
|
// Specifically to write receiver profile information
|
|
|
-export async function writeFile(data: ConnectedServerSocket, filename: string): Promise<boolean> {
|
|
|
+export async function writeFile(data: ConnectedSocketServer, filename: string): Promise<boolean> {
|
|
|
return new Promise((resolve, reject) => {
|
|
|
// Write JSON data to a file
|
|
|
fs.writeFile(`${filename}.json`, JSON.stringify(data, null, 2), (err) => {
|
|
@@ -282,9 +282,9 @@ export async function writeFile(data: ConnectedServerSocket, filename: string):
|
|
|
}
|
|
|
|
|
|
/* For Internal Usage only. Temporary serve as a way for server to keep track of clients. To be replaced in the future with better alternatives. */
|
|
|
-export function addClientToDB(entry: ConnectedClientSocket, filePath: string = 'clients.json'): void {
|
|
|
+export function addClientToDB(entry: ConnectedSocketClient, filePath: string = 'clients.json'): void {
|
|
|
try {
|
|
|
- let data: ConnectedClientSocket[] = [];
|
|
|
+ let data: ConnectedSocketClient[] = [];
|
|
|
|
|
|
// Check if the file exists and load existing data
|
|
|
if (fs.existsSync(filePath)) {
|
|
@@ -298,7 +298,7 @@ export function addClientToDB(entry: ConnectedClientSocket, filePath: string = '
|
|
|
dateCreated: entry.dateCreated,
|
|
|
connectionState: null,
|
|
|
socketInstance: null
|
|
|
- } as unknown as ConnectedClientSocket);
|
|
|
+ } as unknown as ConnectedSocketClient);
|
|
|
|
|
|
// Write the updated array back to the file
|
|
|
fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8');
|
|
@@ -308,7 +308,7 @@ export function addClientToDB(entry: ConnectedClientSocket, filePath: string = '
|
|
|
}
|
|
|
}
|
|
|
|
|
|
-export async function checkIfClientExists(id: string, filePath: string = 'clients.json'): Promise<ConnectedClientSocket> {
|
|
|
+export async function checkIfClientExists(id: string, filePath: string = 'clients.json'): Promise<ConnectedSocketClient> {
|
|
|
return new Promise((resolve, reject) => {
|
|
|
try {
|
|
|
// Check if the file exists
|
|
@@ -368,7 +368,7 @@ export async function checkOwnClientInfo(filename?: string): Promise<{ id: strin
|
|
|
}
|
|
|
|
|
|
// this is for server usage only
|
|
|
-export function startListening(socket: SocketForConnectedClient, client: ConnectedClientSocket, eventListener: Observer<TransportEvent>, oldClient?: boolean): void {
|
|
|
+export function startListening(socket: SocketForConnectedClient, client: ConnectedSocketClient, eventListener: Observer<TransportEvent>, oldClient?: boolean): void {
|
|
|
// notify it's associated retransmission to start releaseing buffer
|
|
|
eventListener.next({
|
|
|
id: uuidv4(),
|