Прослушиватель TCP в .NET 8, развернутый в среде сервера Ubuntu, реагирует медленнее по сравнению с локальным выполнениеC#

Место общения программистов C#
Ответить
Anonymous
 Прослушиватель TCP в .NET 8, развернутый в среде сервера Ubuntu, реагирует медленнее по сравнению с локальным выполнение

Сообщение Anonymous »

У меня есть приложение-прослушиватель TCP, написанное на .NET 8, которое должно прослушивать входящие клиентские соединения, принимать соединения и обрабатывать поступающие сообщения и отвечать клиенту.
Локально, когда я запускаю прослушиватель и клиент TCP, я могу отправлять сообщение от клиента прослушивателю, и прослушиватель отвечает так быстро, как должен.
Ниже приведен код прослушивателя. , Обратите внимание, что прослушиватель обрабатывает сообщение ISO8583

Код: Выделить всё

public class TcpServerHostedService : BackgroundService
{
IPAddress _ipAddress = IPAddress.Parse("127.0.0.1");
int _port = 2000;
private readonly IServiceProvider _serviceProvider;
private readonly IConfiguration _configuration;
private readonly ILogger _logger;

public TcpServerHostedService(IServiceProvider serviceProvider,
IConfiguration configuration,
ILogger logger)
{
_serviceProvider = serviceProvider;
_configuration = configuration;
_logger = logger;
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{

TcpListener listener = new TcpListener(_ipAddress, _port);
listener.Start();
Console.WriteLine("EchoServer started...");
while (!stoppingToken.IsCancellationRequested)
{
Console.WriteLine("Waiting for incoming client connections...");
TcpClient client = await listener.AcceptTcpClientAsync();
Console.WriteLine("Accepted new client connection...");
NetworkStream stream = client.GetStream();

try
{
using (var scope = _serviceProvider.CreateScope())
{
var _transactionService = scope.ServiceProvider.GetRequiredService();
var _mailService = scope.ServiceProvider.GetRequiredService();

while (!stoppingToken.IsCancellationRequested)
{
// Read the header bytes
byte[] headerBytes = new byte[2];
stream.Read(headerBytes, 0, 2);

// Calculate the message length based on the header bytes
int messageLength = headerBytes[0] * 256 + headerBytes[1];

// Receive data from the client
byte[] receiveBuffer = new byte[messageLength];
int bytesRead = await stream.ReadAsync(receiveBuffer, 0, receiveBuffer.Length);

// Convert received bytes to string
string receivedData = Encoding.UTF8.GetString(receiveBuffer, 0, bytesRead);

// Process the ISO 8583 message
string response = await ProcessIsoMessage(receivedData, _transactionService, _mailService);

// Convert string message to bytes using UTF-8 encoding
string message = response;
byte[] messageBytes = Encoding.UTF8.GetBytes(message);

// Get the length of the message and convert it to bytes (using 2 bytes for simplicity)
byte[] resheaderBytes = BitConverter.GetBytes((short)messageBytes.Length);

// Ensure the bytes are in network byte order (big endian)
if (BitConverter.IsLittleEndian)
{
Array.Reverse(resheaderBytes);
}

// Send the length header bytes to the stream
await stream.WriteAsync(resheaderBytes, 0, resheaderBytes.Length);

// Send the actual message bytes to the stream
await stream.WriteAsync(messageBytes, 0, messageBytes.Length);

await stream.FlushAsync();
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "An error occurred on TCP");
}
}
}

private async Task ProcessIsoMessage(string isoMessage, IAfslTransactionService _transactionService, IMailService _mailService)
{
MessageParser.NET.Tools.ISO8583 iso = new MessageParser.NET.Tools.ISO8583();
string[] data = iso.Parse(isoMessage);

Dictionary isoFields = ParseStringArrayToDictionary(data);

string messageTypeCode = isoFields.ContainsKey(0) ? isoFields[0] : "";

if (!string.IsNullOrEmpty(messageTypeCode))
{
Dictionary  result = new Dictionary();

switch (messageTypeCode)
{
case "0100":
result = await _transactionService.ProcessHoldReleaseFunds(isoFields);
break;
case "0200":
result = await _transactionService.ProcessFinancialTransaction(isoFields);
break;
case "0420":
result = await _transactionService.ProcessReversal(isoFields);
break;
case "0800":
result = await _transactionService.ProcessNetworkManagement(isoFields);
break;
}

//Message Type Identifier (Financial Message Response)
string MTI = result[0];

//1. Create Arrays AND Assign corresponding data to each array
string[] DE = ParseDictionaryToStringArray(result);

//3.Use "Build" method of object iso8583 to create a new  message.
string NewISOmsg = iso.Build(DE, MTI);

// Send ISO MESSAGE
return NewISOmsg;
}

return string.Empty;
}

static Dictionary ParseStringArrayToDictionary(string[] array)
{
Dictionary dictionary = new Dictionary();

for (int i = 0; i < array.Length; i++)
{
// Extract key and value from the item
int key = i; // Assuming keys are single digits
string value = array[i];

// Check if key is "129", assign it to key "0" in dictionary
if (key == 129)
{
dictionary[0] = value;
}
// Check if key is "0" or "1", merge them and assign to key "1" in dictionary
else if (key == 0 || key == 1)
{
if (dictionary.ContainsKey(1))
{
dictionary[1] += value;
}
else
{
dictionary[1] = value;
}
}
// Check if the value is not "null"
else if (value != null)
{
dictionary[key] = value;
}
}

return dictionary;
}

static string[] ParseDictionaryToStringArray(Dictionary dictionary)
{
dictionary.Remove(0);
dictionary.Remove(1);
string[] DE = new string[130];

for (int i = 0; i < DE.Length; i++)
{
string value;

dictionary.TryGetValue(i, out value);

DE[i] = !string.IsNullOrEmpty(value) ? value : null;
}

return DE;
}

}
Проблема, с которой я здесь сталкиваюсь, заключается в том, что когда я развертываю прослушиватель на сервере Ubuntu, я отправляю сообщение от TCP-клиента прослушивателю, и для ответа иногда требуется время, даже до 3 -5 минут, и это нехорошо.
Упомянем, что у меня есть сервер Nginx, который обрабатывает входящий запрос для Stream и отправляет его в мое приложение на сервере Ubuntu, но я этого не делаю. думаю, что проблема в nginx, потому что я пытался привязать порт приложения к направлению порта сервера, но у меня все равно возникла та же проблема с задержкой ответа.
Пожалуйста, кто-нибудь сталкивался с такой проблемой и что можно сделать? Я делаю это, чтобы решить эту проблему, потому что это не похоже на проблему с кодом

Подробнее здесь: https://stackoverflow.com/questions/785 ... slowly-com
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»