|
@@ -3,8 +3,9 @@ import { createServer } from 'http';
|
|
import { Server, Socket as SocketForConnectedClient } from 'socket.io';
|
|
import { Server, Socket as SocketForConnectedClient } from 'socket.io';
|
|
import { io, Socket as ClientSocket } from 'socket.io-client';
|
|
import { io, Socket as ClientSocket } from 'socket.io-client';
|
|
import * as fs from 'fs'
|
|
import * as fs from 'fs'
|
|
-import { ReceiverProfile, TransportEventNotification, TransportMessage } from '../interface/ITransport.interface';
|
|
|
|
import { v4 as uuidv4 } from 'uuid'
|
|
import { v4 as uuidv4 } from 'uuid'
|
|
|
|
+import { TransportEvent } from '../interface/connector.interface';
|
|
|
|
+import { ConnectedClientSocket, ConnectedServerSocket } from '../transport/websocket';
|
|
|
|
|
|
export function startSocketServer(port: number): Observable<SocketForConnectedClient> {
|
|
export function startSocketServer(port: number): Observable<SocketForConnectedClient> {
|
|
return new Observable((observer) => {
|
|
return new Observable((observer) => {
|
|
@@ -36,7 +37,7 @@ export async function startClientSocketConnection(serverUrl: string): Promise<Cl
|
|
return new Promise((resolve, reject) => {
|
|
return new Promise((resolve, reject) => {
|
|
try {
|
|
try {
|
|
// let clientSocket = io(serverUrl)
|
|
// let clientSocket = io(serverUrl)
|
|
- let clientSocket = io(serverUrl, {
|
|
|
|
|
|
+ let clientSocket: ClientSocket = io(serverUrl, {
|
|
reconnection: true, // Enable automatic reconnections
|
|
reconnection: true, // Enable automatic reconnections
|
|
reconnectionAttempts: 1000, // Retry up to 10 times
|
|
reconnectionAttempts: 1000, // Retry up to 10 times
|
|
reconnectionDelay: 500, // Start with a 500ms delay
|
|
reconnectionDelay: 500, // Start with a 500ms delay
|
|
@@ -52,17 +53,22 @@ 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
|
|
// 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): Observable<TransportEventNotification> {
|
|
|
|
- return new Observable((eventNotification: Observer<TransportEventNotification>) => {
|
|
|
|
|
|
+export function handleClientSocketConnection(socket: ClientSocket, serversConnected: ConnectedServerSocket[]): Observable<TransportEvent> {
|
|
|
|
+ return new Observable((eventNotification: Observer<TransportEvent>) => {
|
|
let clientName!: string
|
|
let clientName!: string
|
|
let buffer: any[] = []
|
|
let buffer: any[] = []
|
|
- let receiverProfileInfo!: ReceiverProfile
|
|
|
|
|
|
+ let receiverProfileInfo!: ConnectedClientSocket
|
|
|
|
|
|
// Listen for a connection event
|
|
// Listen for a connection event
|
|
socket.on('connect', () => {
|
|
socket.on('connect', () => {
|
|
console.log('Connected to the server:', socket.id)
|
|
console.log('Connected to the server:', socket.id)
|
|
|
|
+ serversConnected.push({
|
|
|
|
+ id: uuidv4(),
|
|
|
|
+ dateCreated: new Date(),
|
|
|
|
+ socketInstance: socket
|
|
|
|
+ })
|
|
if (clientName) {
|
|
if (clientName) {
|
|
- checkOwnClientInfo(clientName).then((profile: ReceiverProfile) => {
|
|
|
|
|
|
+ checkOwnClientInfo(clientName).then((profile: ConnectedClientSocket) => {
|
|
receiverProfileInfo = profile
|
|
receiverProfileInfo = profile
|
|
socket.emit('profile', {
|
|
socket.emit('profile', {
|
|
name: 'Old Client',
|
|
name: 'Old Client',
|
|
@@ -86,23 +92,7 @@ export function handleClientSocketConnection(socket: ClientSocket): Observable<T
|
|
socket.on('message', (msg: any) => {
|
|
socket.on('message', (msg: any) => {
|
|
console.log(`Websocket Client Transport Receieve Msg`, msg.id)
|
|
console.log(`Websocket Client Transport Receieve Msg`, msg.id)
|
|
if (receiverProfileInfo) {
|
|
if (receiverProfileInfo) {
|
|
- eventNotification.next({
|
|
|
|
- event: 'New Message',
|
|
|
|
- description: 'Received new message',
|
|
|
|
- transportType: 'WEBSOCKET',
|
|
|
|
- data: {
|
|
|
|
- receiverID: receiverProfileInfo.uuid,
|
|
|
|
- receiverName: receiverProfileInfo.name,
|
|
|
|
- date: new Date(),
|
|
|
|
- payload: msg
|
|
|
|
- }
|
|
|
|
- })
|
|
|
|
- // incomingMessage.next({
|
|
|
|
- // id: msg.header.MessageID,
|
|
|
|
- // receiverID: receiverProfileInfo.uuid,
|
|
|
|
- // payload: msg,
|
|
|
|
- // event: 'New Message'
|
|
|
|
- // })
|
|
|
|
|
|
+ // publish to event
|
|
} else {
|
|
} else {
|
|
// Do nothing. just store in local array first. Cannot process without information. but then again, don['t need information if acting as client
|
|
// Do nothing. just store in local array first. Cannot process without information. but then again, don['t need information if acting as client
|
|
// but for consistency sake, will impose the standard
|
|
// but for consistency sake, will impose the standard
|
|
@@ -113,33 +103,23 @@ export function handleClientSocketConnection(socket: ClientSocket): Observable<T
|
|
socket.on('profile', (data: { name: string, message: any }) => {
|
|
socket.on('profile', (data: { name: string, message: any }) => {
|
|
// console.log(data)
|
|
// console.log(data)
|
|
if (data.name == 'New Profile') {
|
|
if (data.name == 'New Profile') {
|
|
- console.log(`Assigned client Name: ${(data.message as ReceiverProfile).name}`)
|
|
|
|
- receiverProfileInfo = data.message as ReceiverProfile
|
|
|
|
- writeFile(data.message as ReceiverProfile, (data.message as ReceiverProfile).name).then(() => {
|
|
|
|
- clientName = receiverProfileInfo.name
|
|
|
|
|
|
+ console.log(`Assigned client Name: ${(data.message as ConnectedClientSocket).id}`)
|
|
|
|
+ receiverProfileInfo = data.message as ConnectedClientSocket
|
|
|
|
+ writeFile(data.message as ConnectedClientSocket, (data.message as ConnectedClientSocket).id).then(() => {
|
|
|
|
+ clientName = receiverProfileInfo.id
|
|
// broadcast event to allow retransmission to release buffer
|
|
// broadcast event to allow retransmission to release buffer
|
|
- eventNotification.next({
|
|
|
|
- event: 'Connection',
|
|
|
|
- description: 'Profile acquired || updated and stored',
|
|
|
|
- transportType: 'WEBSOCKET',
|
|
|
|
- data: {
|
|
|
|
- receiverID: receiverProfileInfo.uuid,
|
|
|
|
- receiverName: receiverProfileInfo.name,
|
|
|
|
- date: new Date(),
|
|
|
|
- payload: receiverProfileInfo
|
|
|
|
- }
|
|
|
|
- })
|
|
|
|
|
|
+
|
|
}).catch((error) => { }) // do nothing at the moment.
|
|
}).catch((error) => { }) // do nothing at the moment.
|
|
}
|
|
}
|
|
if (data.name == 'Adjusted Profile') {
|
|
if (data.name == 'Adjusted Profile') {
|
|
- console.log(`Assigned client Name: ${(data.message as ReceiverProfile).name}`)
|
|
|
|
- receiverProfileInfo = data.message as ReceiverProfile
|
|
|
|
- writeFile(data.message as ReceiverProfile, (data.message as ReceiverProfile).name).then(() => {
|
|
|
|
|
|
+ console.log(`Assigned client Name: ${(data.message as ConnectedClientSocket).id}`)
|
|
|
|
+ receiverProfileInfo = data.message as ConnectedClientSocket
|
|
|
|
+ writeFile(data.message as ConnectedClientSocket, (data.message as ConnectedClientSocket).id).then(() => {
|
|
// broadcast event to allow retransmission to release buffer
|
|
// broadcast event to allow retransmission to release buffer
|
|
eventNotification.next({
|
|
eventNotification.next({
|
|
- event: 'Connection',
|
|
|
|
- description: 'Profile acquired || updated and stored',
|
|
|
|
- transportType: 'WEBSOCKET',
|
|
|
|
|
|
+ id: uuidv4(),
|
|
|
|
+ event: 'Client Reconnected',
|
|
|
|
+ data: ''
|
|
})
|
|
})
|
|
}).catch((error) => { }) // do nothing at the moment.
|
|
}).catch((error) => { }) // do nothing at the moment.
|
|
}
|
|
}
|
|
@@ -160,9 +140,9 @@ export function handleClientSocketConnection(socket: ClientSocket): Observable<T
|
|
console.log('Websocket Client disconnected from the server');
|
|
console.log('Websocket Client disconnected from the server');
|
|
if (receiverProfileInfo) {
|
|
if (receiverProfileInfo) {
|
|
eventNotification.next({
|
|
eventNotification.next({
|
|
- event: 'Disconnection',
|
|
|
|
- description: 'Disconnected from the server',
|
|
|
|
- transportType: 'WEBSOCKET'
|
|
|
|
|
|
+ id: uuidv4(),
|
|
|
|
+ event: `Client Disconnected`,
|
|
|
|
+ data: ''
|
|
})
|
|
})
|
|
}
|
|
}
|
|
});
|
|
});
|
|
@@ -170,55 +150,39 @@ export function handleClientSocketConnection(socket: ClientSocket): Observable<T
|
|
}
|
|
}
|
|
|
|
|
|
// For SERVER Usage: set up socket listeners to start listening for different events
|
|
// For SERVER Usage: set up socket listeners to start listening for different events
|
|
-export function handleNewSocketClient(socket: SocketForConnectedClient, socketReceiverProfile: ReceiverProfile[]): Observable<TransportEventNotification> {
|
|
|
|
- return new Observable((event: Observer<TransportEventNotification>) => {
|
|
|
|
|
|
+export function handleNewSocketClient(socket: SocketForConnectedClient, connectedClientSocket: ConnectedClientSocket[]): Observable<TransportEvent> {
|
|
|
|
+ return new Observable((event: Observer<TransportEvent>) => {
|
|
console.log(`Setting up listeners for socket:${socket.id}`)
|
|
console.log(`Setting up listeners for socket:${socket.id}`)
|
|
// returns the socket client instance
|
|
// returns the socket client instance
|
|
// listen to receiver's initiotion first before assigning 'credentials'
|
|
// listen to receiver's initiotion first before assigning 'credentials'
|
|
- socket.on(`profile`, (message: { name: string, data: ReceiverProfile }) => {
|
|
|
|
|
|
+ socket.on(`profile`, (message: { name: string, data: any }) => {
|
|
if (message.name == 'New Client') {
|
|
if (message.name == 'New Client') {
|
|
- let receiverProfile: ReceiverProfile = {
|
|
|
|
- uuid: uuidv4(),
|
|
|
|
- name: `Client${uuidv4()}`,
|
|
|
|
|
|
+ let clientInstance: ConnectedClientSocket = {
|
|
|
|
+ id: uuidv4(),
|
|
dateCreated: new Date(),
|
|
dateCreated: new Date(),
|
|
- transportType: `WEBSOCKET`,
|
|
|
|
- eventNotification: new Subject(),
|
|
|
|
- instance: socket
|
|
|
|
|
|
+ socketInstance: socket
|
|
}
|
|
}
|
|
// publish first event notification
|
|
// publish first event notification
|
|
event.next({
|
|
event.next({
|
|
- event: 'Connection',
|
|
|
|
- description: 'New Client Connected',
|
|
|
|
- transportType: 'WEBSOCKET',
|
|
|
|
- data: {
|
|
|
|
- receiverID: receiverProfile.uuid,
|
|
|
|
- receiverName: receiverProfile.name,
|
|
|
|
- date: new Date(),
|
|
|
|
- payload: receiverProfile
|
|
|
|
- }
|
|
|
|
|
|
+ id: uuidv4(),
|
|
|
|
+ event: `New Client`,
|
|
|
|
+ data: clientInstance
|
|
})
|
|
})
|
|
// send to receiver for reference
|
|
// send to receiver for reference
|
|
socket.emit('profile', {
|
|
socket.emit('profile', {
|
|
- name: `New Profile`, message: {
|
|
|
|
- uuid: receiverProfile.uuid,
|
|
|
|
- name: receiverProfile.name,
|
|
|
|
- dateCreated: receiverProfile.dateCreated,
|
|
|
|
- transportType: `WEBSOCKET`,
|
|
|
|
- eventNotification: null,
|
|
|
|
- instance: null // have to put null, otherwise circular reference maximum stack error
|
|
|
|
- }
|
|
|
|
|
|
+ name: `New Profile`, message: clientInstance
|
|
})
|
|
})
|
|
- socketReceiverProfile.push(receiverProfile)
|
|
|
|
- startListening(socket, receiverProfile)
|
|
|
|
|
|
+ // Update connected clientInstance info to adapter
|
|
|
|
+ connectedClientSocket.push(clientInstance)
|
|
|
|
+ startListening(socket, clientInstance, event)
|
|
} else {
|
|
} else {
|
|
// update first
|
|
// update first
|
|
- let receiverProfile: ReceiverProfile | undefined = socketReceiverProfile.find(obj => obj.uuid === message.data.uuid)
|
|
|
|
- if (receiverProfile) {
|
|
|
|
- console.log(`Profile ${receiverProfile.uuid} Found`)
|
|
|
|
- receiverProfile.instance = socket
|
|
|
|
- socket.emit('profile', { name: 'Adjusted Profile', message: receiverProfile })
|
|
|
|
|
|
+ let clientInstance: ConnectedClientSocket | undefined = connectedClientSocket.find(obj => obj.id === message.data.id)
|
|
|
|
+ if (clientInstance) {
|
|
|
|
+ console.log(`Socket Client ${clientInstance.id} Found`)
|
|
|
|
+ socket.emit('profile', { name: 'Adjusted Profile', message: clientInstance })
|
|
// need to start listening again, because it's assigned a different socket instance this time round
|
|
// need to start listening again, because it's assigned a different socket instance this time round
|
|
- startListening(socket, receiverProfile)
|
|
|
|
|
|
+ startListening(socket, clientInstance, event)
|
|
} else {
|
|
} else {
|
|
console.log(`Profile Not Found`)
|
|
console.log(`Profile Not Found`)
|
|
socket.emit('profile', { name: 'Error', message: 'Receiver Profile Not found' })
|
|
socket.emit('profile', { name: 'Error', message: 'Receiver Profile Not found' })
|
|
@@ -230,7 +194,7 @@ export function handleNewSocketClient(socket: SocketForConnectedClient, socketRe
|
|
|
|
|
|
|
|
|
|
// Specifically to write receiver profile information
|
|
// Specifically to write receiver profile information
|
|
-export async function writeFile(data: ReceiverProfile, filename: string): Promise<boolean> {
|
|
|
|
|
|
+export async function writeFile(data: ConnectedClientSocket, filename: string): Promise<boolean> {
|
|
return new Promise((resolve, reject) => {
|
|
return new Promise((resolve, reject) => {
|
|
// Write JSON data to a file
|
|
// Write JSON data to a file
|
|
fs.writeFile(`${filename}.json`, JSON.stringify(data, null, 2), (err) => {
|
|
fs.writeFile(`${filename}.json`, JSON.stringify(data, null, 2), (err) => {
|
|
@@ -248,7 +212,7 @@ export async function writeFile(data: ReceiverProfile, filename: string): Promis
|
|
|
|
|
|
|
|
|
|
// Check if filename exists. Return profile information if there's any
|
|
// Check if filename exists. Return profile information if there's any
|
|
-export async function checkOwnClientInfo(filename: string): Promise<ReceiverProfile> {
|
|
|
|
|
|
+export async function checkOwnClientInfo(filename: string): Promise<ConnectedClientSocket> {
|
|
return new Promise((resolve, reject) => {
|
|
return new Promise((resolve, reject) => {
|
|
// Check if the file exists
|
|
// Check if the file exists
|
|
if (fs.existsSync(`${filename}.json`)) {
|
|
if (fs.existsSync(`${filename}.json`)) {
|
|
@@ -277,43 +241,58 @@ export async function checkOwnClientInfo(filename: string): Promise<ReceiverProf
|
|
})
|
|
})
|
|
}
|
|
}
|
|
|
|
|
|
-export function startListening(socket: SocketForConnectedClient, receiverProfile: ReceiverProfile): void {
|
|
|
|
|
|
+export function startListening(socket: SocketForConnectedClient, client: ConnectedClientSocket, eventListener: Observer<TransportEvent>): void {
|
|
/* Generally, we don't need this unless in the case of being the receiver */
|
|
/* Generally, we don't need this unless in the case of being the receiver */
|
|
socket.on('message', (message: any) => {
|
|
socket.on('message', (message: any) => {
|
|
- // here
|
|
|
|
|
|
+ eventListener.next({
|
|
|
|
+ id: uuidv4(),
|
|
|
|
+ event: 'New Message',
|
|
|
|
+ data: {
|
|
|
|
+ clientID: client.id,
|
|
|
|
+ dateReceived: new Date(),
|
|
|
|
+ payload: message
|
|
|
|
+ }
|
|
|
|
+ })
|
|
})
|
|
})
|
|
|
|
|
|
- socket.on('request', (request: any) => {
|
|
|
|
|
|
+ socket.on('request', (message: any) => {
|
|
// here : Let's say there's a subcsription request here
|
|
// here : Let's say there's a subcsription request here
|
|
- receiverProfile.eventNotification.next({
|
|
|
|
|
|
+ eventListener.next({
|
|
|
|
+ id: uuidv4(),
|
|
event: 'New Message',
|
|
event: 'New Message',
|
|
- description: 'Incoming request',
|
|
|
|
- transportType: 'WEBSOCKET',
|
|
|
|
data: {
|
|
data: {
|
|
- receiverID: receiverProfile.uuid,
|
|
|
|
- receiverName: receiverProfile.name,
|
|
|
|
- date: new Date(),
|
|
|
|
- payload: request
|
|
|
|
|
|
+ clientID: client.id,
|
|
|
|
+ dateReceived: new Date(),
|
|
|
|
+ payload: message
|
|
}
|
|
}
|
|
})
|
|
})
|
|
})
|
|
})
|
|
|
|
|
|
socket.on('notification', (notification: any) => {
|
|
socket.on('notification', (notification: any) => {
|
|
// logic here
|
|
// logic here
|
|
|
|
+ eventListener.next({
|
|
|
|
+ id: uuidv4(),
|
|
|
|
+ event: `Notification`,
|
|
|
|
+ data: {
|
|
|
|
+ clientID: client.id,
|
|
|
|
+ dateReceived: new Date(),
|
|
|
|
+ payload: notification
|
|
|
|
+ }
|
|
|
|
+ })
|
|
})
|
|
})
|
|
|
|
|
|
socket.on('disconnect', () => {
|
|
socket.on('disconnect', () => {
|
|
- receiverProfile.eventNotification.next(
|
|
|
|
- {
|
|
|
|
- event: 'Disconnection',
|
|
|
|
- description: `Existing Client ${receiverProfile.uuid} disonnected`,
|
|
|
|
- transportType: `WEBSOCKET`,
|
|
|
|
- data: {
|
|
|
|
- receiverID: receiverProfile.uuid,
|
|
|
|
- receiverName: receiverProfile.name,
|
|
|
|
- date: new Date(),
|
|
|
|
- }
|
|
|
|
|
|
+ eventListener.next({
|
|
|
|
+ id: uuidv4(),
|
|
|
|
+ event: 'Server Disconnected',
|
|
|
|
+ data: {
|
|
|
|
+ clientID: client.id,
|
|
|
|
+ time: new Date()
|
|
}
|
|
}
|
|
- )
|
|
|
|
|
|
+ })
|
|
|
|
+ eventListener.error(`Client ${client.id} disconnected. Terminating this observable event for this client socket...`)
|
|
|
|
+ eventListener.complete()
|
|
})
|
|
})
|
|
-}
|
|
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+
|