Commit 191cdc3f authored by Jose Hugo Torres's avatar Jose Hugo Torres
Browse files

Servidor #17

parent 6ad5b3de
...@@ -113,7 +113,7 @@ public class ServidorGatewayCHEC(string ipGateway, int ptoGateway, string ipPOSB ...@@ -113,7 +113,7 @@ public class ServidorGatewayCHEC(string ipGateway, int ptoGateway, string ipPOSB
Log.Information("Servidor GATEWAY CHEC socket en {ip} : {puerto}, proceso id {id}", IpGateway, PuertoGateway, idProceso); Log.Information("Servidor GATEWAY CHEC socket en {ip} : {puerto}, proceso id {id}", IpGateway, PuertoGateway, idProceso);
if (_isDebug) if (_isDebug)
{ {
Log.Debug("Versión framework {version} # 14", Environment.Version); Log.Debug("Versión framework {version} # 17", Environment.Version);
Log.Debug("Tcp Socket configuración:"); Log.Debug("Tcp Socket configuración:");
Log.Debug($" Blocking {tcpSocket.Blocking}"); Log.Debug($" Blocking {tcpSocket.Blocking}");
Log.Debug($" ExclusiveAddressUse {tcpSocket.ExclusiveAddressUse}"); Log.Debug($" ExclusiveAddressUse {tcpSocket.ExclusiveAddressUse}");
...@@ -140,7 +140,8 @@ public class ServidorGatewayCHEC(string ipGateway, int ptoGateway, string ipPOSB ...@@ -140,7 +140,8 @@ public class ServidorGatewayCHEC(string ipGateway, int ptoGateway, string ipPOSB
((IPEndPoint)clienteCHEC.RemoteEndPoint).Port.ToString()); ((IPEndPoint)clienteCHEC.RemoteEndPoint).Port.ToString());
// Activa el POSBC // Activa el POSBC
var tareaRemiteRespuestaPOSBC = Task.Run(() => ProcesaSalidaPOSBC(clienteCHEC, _posbc.Socket)); var tareaRemiteRespuestaPOSBC = Task.Run(() => ProcesaSalidaPOSBC(clienteCHEC, _posbc.Socket));
var tareaAceptaEntradasCHEC = Task.Run(() => AceptaEntradasCHEC(clienteCHEC)); ProcesarConexion(clienteCHEC, _posbc.Socket);
//var tareaAceptaEntradasCHEC = Task.Run(() => AceptaEntradasCHEC(clienteCHEC));
} }
} }
finally finally
...@@ -151,85 +152,144 @@ public class ServidorGatewayCHEC(string ipGateway, int ptoGateway, string ipPOSB ...@@ -151,85 +152,144 @@ public class ServidorGatewayCHEC(string ipGateway, int ptoGateway, string ipPOSB
} }
} }
/// <summary> public void ProcesarConexion(Socket clienteCHEC, Socket clientePOSBC)
/// Acepta entrada de datos desde CHEC.
/// Procesa la entrada.
/// </summary>
/// <param name="cliente">Socket de conexión a CHEC.</param>
/// <returns></returns>
public async Task AceptaEntradasCHEC(Socket cliente)
{ {
var taskId = Task.CurrentId?.ToString() ?? "no-task"; bool continua = true;
_socketCHEC = cliente; while (continua)
Log.Debug("{tid} Tarea acepta entradas iniciada", taskId);
while (true)
{ {
try
{
// Lee mensajes hasta que llegue mensaje de terminación o socket cerrado por el cliente.
// Lee longitud mensaje entrante, 4 bytes.
Log.Debug("GTWY Esperando mensaje...");
var bufferLongitud = new byte[4];
int bytesLeidos = 0;
while (bytesLeidos < 4)
{
bytesLeidos += clienteCHEC.Receive(bufferLongitud, bytesLeidos, bufferLongitud.Length, SocketFlags.None);
}
// ------------------- LECTURA SINCRONICA // Lee porción de datos del mensaje, hasta la longitud indicada en los 4 primeros bytes.
int longitudMensaje = Util.LongitudCodificada(bufferLongitud);
var bufferEntrada = new byte[longitudMensaje];
bytesLeidos = 0;
while (bytesLeidos < longitudMensaje)
{
bytesLeidos += clienteCHEC.Receive(bufferEntrada, bytesLeidos, bufferEntrada.Length, SocketFlags.None);
}
Log.Information("CHEC -> GTWY Nuevo mensaje {bytes} bytes.", bytesLeidos);
// Lee longitud mensaje entrante, 4 bytes.
Log.Information("{tid} Esperando CHEC", taskId); byte[] mensajeEntrada = Util.ConcatenaArreglosBytes(bufferLongitud, bufferEntrada);
var bufferLongitud = new byte[4]; // Enviar mensaje de entrada a POSBC y retornar respuestas.
int bytesLeidos = 0;
while (bytesLeidos < 4) // Remite mensaje.
clientePOSBC.Send(mensajeEntrada);
_nroMsjEntradaCHEC++;
Log.Information("GTWY -> POSBC envia mensaje {bytes} bytes.", mensajeEntrada.Length);
//byte[] mensajeSalida = Entorno<EntornoPOSBC>.Instancia.get().ClientePOSBC.EnviaRecibe(mensajeEntrada);
// Remitir respuestas sin cambio a CHEC.
//clienteCHEC.Send(mensajeSalida, 0, mensajeSalida.Length, SocketFlags.None);
}
catch (SocketException ex)
{ {
bytesLeidos += cliente.Receive(bufferLongitud, bytesLeidos, bufferLongitud.Length, SocketFlags.None); if (ex.SocketErrorCode == SocketError.ConnectionAborted)
{
Log.Warning("Conexión abortada por el equipo remoto.");
}
else
{
Log.Error("Error de Socket: {error}", ex);
}
continua = false;
} }
// Lee porción de datos del mensaje, hasta la longitud indicada en los 4 primeros bytes. catch (Exception e)
int longitudMensaje = Util.LongitudCodificada(bufferLongitud);
Log.Debug("{tid} CHEC -> GTWY entra nuevo mensaje, longitud en cabecera {nroBytes}", taskId, longitudMensaje);
var bufferEntrada = new byte[longitudMensaje];
bytesLeidos = 0;
while (bytesLeidos < longitudMensaje)
{ {
bytesLeidos += cliente.Receive(bufferEntrada, bytesLeidos, bufferEntrada.Length, SocketFlags.None); Log.Error("Error : {error}", e);
continua = false;
} }
}
}
// ---------------------- LECTURA ASINCRONICA /// <summary>
/// Acepta entrada de datos desde CHEC.
/// Procesa la entrada.
/// </summary>
/// <param name="cliente">Socket de conexión a CHEC.</param>
/// <returns></returns>
// public async Task AceptaEntradasCHEC(Socket cliente)
// {
// var taskId = Task.CurrentId?.ToString() ?? "no-task";
// _socketCHEC = cliente;
// Log.Debug("{tid} Tarea acepta entradas iniciada", taskId);
// while (true)
// {
// Lee los primeros 4 bytes de los datos de entrada, los cuales indican // // ------------------- LECTURA SINCRONICA
// la longitud del resto del mensaje.
//int nroBytesLeidos = await cliente.ReceiveAsync(new ArraySegment<byte>(bufferLongitud), SocketFlags.None);
// // Lee longitud mensaje entrante, 4 bytes.
// Log.Information("{tid} Esperando CHEC", taskId);
// var bufferLongitud = new byte[4];
// int bytesLeidos = 0;
// while (bytesLeidos < 4)
// {
// bytesLeidos += cliente.Receive(bufferLongitud, bytesLeidos, bufferLongitud.Length, SocketFlags.None);
// }
// // Lee porción de datos del mensaje, hasta la longitud indicada en los 4 primeros bytes.
// int longitudMensaje = Util.LongitudCodificada(bufferLongitud);
// Log.Debug("{tid} CHEC -> GTWY entra nuevo mensaje, longitud en cabecera {nroBytes}", taskId, longitudMensaje);
// var bufferEntrada = new byte[longitudMensaje];
// bytesLeidos = 0;
// while (bytesLeidos < longitudMensaje)
// {
// bytesLeidos += cliente.Receive(bufferEntrada, bytesLeidos, bufferEntrada.Length, SocketFlags.None);
// }
// Si el número de bytes leidos es cero, la conexión se ha cerrado. // // ---------------------- LECTURA ASINCRONICA
// El método Receive es sincróno, luego si retorna sin datos, es que no hay conexión.
// Mientras tenga conexión, se queda esperando datos.
// if (nroBytesLeidos == 0)
// {
// Log.Warning("{tid} CHEC -> GTWY emite 0 bytes - señal cierra conexión.");
// break;
// }
// int longitudMensaje = Util.LongitudCodificada(bufferLongitud); // // Lee los primeros 4 bytes de los datos de entrada, los cuales indican
// Log.Debug("{tid} CHEC -> GTWY bytes cabecera {nroBytes}, longitud cuerpo mensaje {longitud}", taskId, nroBytesLeidos, longitudMensaje); // // la longitud del resto del mensaje.
// // Prepara buffer de entrada según la longitud esperada del mensaje. // //int nroBytesLeidos = await cliente.ReceiveAsync(new ArraySegment<byte>(bufferLongitud), SocketFlags.None);
// var bufferMensaje = new byte[longitudMensaje];
// nroBytesLeidos = await cliente.ReceiveAsync(new ArraySegment<byte>(bufferMensaje), SocketFlags.None);
_nroMsjEntradaCHEC++;
Log.Information("{tid} CHEC -> GTWY nuevo mensaje #{nro} - cuerpo {bytes} bytes", taskId, _nroMsjEntradaCHEC, bytesLeidos);
// Arreglo de bytes de entrada se transforma en string, // // Si el número de bytes leidos es cero, la conexión se ha cerrado.
// constituye el mensaje. // // El método Receive es sincróno, luego si retorna sin datos, es que no hay conexión.
string mensaje = Encoding.UTF8.GetString(bufferEntrada, 0, bytesLeidos); // // Mientras tenga conexión, se queda esperando datos.
if (bytesLeidos != longitudMensaje) // // if (nroBytesLeidos == 0)
{ // // {
Log.Warning("{tid} Longitud en cabecera {longitudMensaje} no corresponde a longitud {bytesLeidos} mensaje leido.", taskId, longitudMensaje, bytesLeidos); // // Log.Warning("{tid} CHEC -> GTWY emite 0 bytes - señal cierra conexión.");
} // // break;
Log.Verbose("{tid} CHEC -> GTWY mensaje\n{msj}", taskId, mensaje); // // }
// Se agrega mensaje a la cola de entrada de mensajes. // // int longitudMensaje = Util.LongitudCodificada(bufferLongitud);
// await _canalEntrada.Writer.WriteAsync(mensaje); // // Log.Debug("{tid} CHEC -> GTWY bytes cabecera {nroBytes}, longitud cuerpo mensaje {longitud}", taskId, nroBytesLeidos, longitudMensaje);
// Log.Debug("{tid} mensaje {nro} -> [cola entrada]", taskId, _nroMsjEntrada); // // // Prepara buffer de entrada según la longitud esperada del mensaje.
// // var bufferMensaje = new byte[longitudMensaje];
// // nroBytesLeidos = await cliente.ReceiveAsync(new ArraySegment<byte>(bufferMensaje), SocketFlags.None);
// Punto de procesamiento mensajes desde CHEC antes de enviar a POSBC. // _nroMsjEntradaCHEC++;
string mensajeProcesado = ProcesaMensajeCHEC(mensaje); // Log.Information("{tid} CHEC -> GTWY nuevo mensaje #{nro} - cuerpo {bytes} bytes", taskId, _nroMsjEntradaCHEC, bytesLeidos);
await _posbc.Envia(mensajeProcesado);
} // // Arreglo de bytes de entrada se transforma en string,
cliente.Close(); // // constituye el mensaje.
Log.Warning("{tid} Tarea acepta entradas CHEC TERMINADA", taskId); // string mensaje = Encoding.UTF8.GetString(bufferEntrada, 0, bytesLeidos);
} // if (bytesLeidos != longitudMensaje)
// {
// Log.Warning("{tid} Longitud en cabecera {longitudMensaje} no corresponde a longitud {bytesLeidos} mensaje leido.", taskId, longitudMensaje, bytesLeidos);
// }
// Log.Verbose("{tid} CHEC -> GTWY mensaje\n{msj}", taskId, mensaje);
// // Se agrega mensaje a la cola de entrada de mensajes.
// // await _canalEntrada.Writer.WriteAsync(mensaje);
// // Log.Debug("{tid} mensaje {nro} -> [cola entrada]", taskId, _nroMsjEntrada);
// // Punto de procesamiento mensajes desde CHEC antes de enviar a POSBC.
// string mensajeProcesado = ProcesaMensajeCHEC(mensaje);
// await _posbc.Envia(mensajeProcesado);
// }
// cliente.Close();
// Log.Warning("{tid} Tarea acepta entradas CHEC TERMINADA", taskId);
// }
/// <summary> /// <summary>
/// Procesa los mensajes d entrada CHEC. /// Procesa los mensajes d entrada CHEC.
...@@ -238,12 +298,12 @@ public class ServidorGatewayCHEC(string ipGateway, int ptoGateway, string ipPOSB ...@@ -238,12 +298,12 @@ public class ServidorGatewayCHEC(string ipGateway, int ptoGateway, string ipPOSB
/// </summary> /// </summary>
/// <param name="mensaje"></param> /// <param name="mensaje"></param>
/// <returns></returns> /// <returns></returns>
public string ProcesaMensajeCHEC(string mensaje) // public string ProcesaMensajeCHEC(string mensaje)
{ // {
Log.Debug("GTWY procesador mensaje CHEC para POSBC invocado."); // Log.Debug("GTWY procesador mensaje CHEC para POSBC invocado.");
var copiaMensaje = new String(mensaje); // var copiaMensaje = new String(mensaje);
return copiaMensaje; // return copiaMensaje;
} // }
/// <summary> /// <summary>
...@@ -276,6 +336,31 @@ public class ServidorGatewayCHEC(string ipGateway, int ptoGateway, string ipPOSB ...@@ -276,6 +336,31 @@ public class ServidorGatewayCHEC(string ipGateway, int ptoGateway, string ipPOSB
} }
_nroMsjEntradaPOSBC++; _nroMsjEntradaPOSBC++;
Log.Information("{tid} GTWY <- POSBC {nro} - {bytes} bytes cuerpo", taskId, _nroMsjEntradaPOSBC, bytesLeidos); Log.Information("{tid} GTWY <- POSBC {nro} - {bytes} bytes cuerpo", taskId, _nroMsjEntradaPOSBC, bytesLeidos);
// Usar un MemoryStream para manejar datos de longitud arbitrariai
//Leer la respuesta del servidor
// byte[] buffer = new byte[1024]; // Tamaño del buffer inicial
// int totalBytesRead = 0;
// int bytesRead;
// byte[] bufferEntrada;
// using (var ms = new System.IO.MemoryStream(1024))
// {
// while ((bytesRead = clientePOSBC.Receive(buffer)) > 0)
// {
// ms.Write(buffer, 0, bytesRead);
// totalBytesRead += bytesRead;
// // Romper el ciclo si se ha leído todo el mensaje
// if (clientePOSBC.Available == 0) break;
// }
// // Obtener todos los datos recibidos como un arreglo de bytes
// bufferEntrada = ms.ToArray();
// }
// Arreglo de bytes de entrada se transforma en string, // Arreglo de bytes de entrada se transforma en string,
// constituye el mensaje. // constituye el mensaje.
...@@ -287,7 +372,8 @@ public class ServidorGatewayCHEC(string ipGateway, int ptoGateway, string ipPOSB ...@@ -287,7 +372,8 @@ public class ServidorGatewayCHEC(string ipGateway, int ptoGateway, string ipPOSB
if (mensajeProcesado.Length > 0) if (mensajeProcesado.Length > 0)
{ {
byte[] bufferSalida = Util.ConvierteEnBufferBytes(mensajeProcesado); byte[] bufferSalida = Util.ConvierteEnBufferBytes(mensajeProcesado);
await clienteCHEC.SendAsync(bufferSalida); //byte[] mensajeEntrada = Util.ConcatenaArreglosBytes(bufferLongitud, bufferEntrada);
await clienteCHEC.SendAsync(bufferEntrada);
_nroMsjSalidaCHEC++; _nroMsjSalidaCHEC++;
Log.Information("{tid} CHEC <- GTWY {nro} - {bytes} bytes total", taskId, _nroMsjSalidaCHEC, bufferSalida.Length); Log.Information("{tid} CHEC <- GTWY {nro} - {bytes} bytes total", taskId, _nroMsjSalidaCHEC, bufferSalida.Length);
Log.Verbose("{tid} CHEC <- GTWY mensaje\n{msj}", taskId, mensaje); Log.Verbose("{tid} CHEC <- GTWY mensaje\n{msj}", taskId, mensaje);
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment