network chunk v9
This commit is contained in:
@@ -1,11 +1,13 @@
|
|||||||
import { ParsedMessage } from '../message_handler';
|
import { ParsedMessage } from '../message_handler';
|
||||||
import { OperationHandler } from '../operations_base/operation_handler';
|
import { OperationHandler } from '../operations_base/operation_handler';
|
||||||
|
import { exec } from 'child_process';
|
||||||
|
|
||||||
export abstract class SocketCommunicatorBase {
|
export abstract class SocketCommunicatorBase {
|
||||||
protected readonly ip: string;
|
protected readonly ip: string;
|
||||||
protected readonly port: number;
|
protected readonly port: number;
|
||||||
protected readonly operationHandler: OperationHandler;
|
protected readonly operationHandler: OperationHandler;
|
||||||
protected handlerResult: ParsedMessage | null;
|
protected handlerResult: ParsedMessage | null;
|
||||||
|
protected networkSpeed: number | null = null; // Estimated network speed in bytes/ms
|
||||||
|
|
||||||
protected constructor(ip: string, port: number, operationHandler: OperationHandler) {
|
protected constructor(ip: string, port: number, operationHandler: OperationHandler) {
|
||||||
this.ip = ip;
|
this.ip = ip;
|
||||||
@@ -18,4 +20,37 @@ export abstract class SocketCommunicatorBase {
|
|||||||
getHandlerResult(): ParsedMessage | null {
|
getHandlerResult(): ParsedMessage | null {
|
||||||
return this.handlerResult;
|
return this.handlerResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected async scanNetworkLatency(): Promise<number> {
|
||||||
|
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<number> {
|
||||||
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user