From b9bef884148f271d3e2b5c77358e293157b8f493 Mon Sep 17 00:00:00 2001 From: andrei-mihnea-cerbu Date: Wed, 13 Nov 2024 10:34:24 +0200 Subject: [PATCH] network chunk v9 --- .../socket_communicator_base.ts | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/UC/src/network/socket_communicator/socket_communicator_base.ts b/UC/src/network/socket_communicator/socket_communicator_base.ts index cbe8e7d..5176fdd 100644 --- a/UC/src/network/socket_communicator/socket_communicator_base.ts +++ b/UC/src/network/socket_communicator/socket_communicator_base.ts @@ -1,11 +1,13 @@ import { ParsedMessage } from '../message_handler'; import { OperationHandler } from '../operations_base/operation_handler'; +import { exec } from 'child_process'; export abstract class SocketCommunicatorBase { protected readonly ip: string; protected readonly port: number; protected readonly operationHandler: OperationHandler; protected handlerResult: ParsedMessage | null; + protected networkSpeed: number | null = null; // Estimated network speed in bytes/ms protected constructor(ip: string, port: number, operationHandler: OperationHandler) { this.ip = ip; @@ -18,4 +20,37 @@ export abstract class SocketCommunicatorBase { getHandlerResult(): ParsedMessage | null { return this.handlerResult; } + + protected async scanNetworkLatency(): Promise { + const targetIp = this.ip; // Use the IP from the superclass + return new Promise((resolve, reject) => { + exec(`ping -c 1 ${targetIp}`, (error, stdout) => { + if (error) { + console.error(`Ping error: ${error}`); + return reject(error); + } + + const match = stdout.match(/time=([\d.]+) ms/); + if (match && match[1]) { + const latency = parseFloat(match[1]); + console.log(`Network latency to ${targetIp} is approximately ${latency} ms`); + resolve(latency); + } else { + reject(new Error('Unable to determine latency from ping output.')); + } + }); + }); + } + + protected async calculateOptimalChunkSize(messageLength: number): Promise { + this.networkSpeed = await this.scanNetworkLatency(); + let chunkSize = Math.min(Math.max(512, Math.floor(5000 / this.networkSpeed)), 1024); + + // Ensure chunk size aligns with base64 encoding (multiple of 4) + while (messageLength % chunkSize !== 0 && chunkSize > 0) { + chunkSize -= 4; + } + + return chunkSize || 1024; + } }