Skip to content
GitLab
Menu
Projects
Groups
Snippets
/
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Menu
Open sidebar
Brayan Sarmiento
API-Gateway-CHEC
Commits
191cdc3f
Commit
191cdc3f
authored
Jun 23, 2024
by
Jose Hugo Torres
Browse files
Servidor #17
parent
6ad5b3de
Changes
1
Hide whitespace changes
Inline
Side-by-side
gatewayGK/Servidor/GatewayCHEC.cs
View file @
191cdc3f
...
...
@@ -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
);
if
(
_isDebug
)
{
Log
.
Debug
(
"Versión framework {version} # 1
4
"
,
Environment
.
Version
);
Log
.
Debug
(
"Versión framework {version} # 1
7
"
,
Environment
.
Version
);
Log
.
Debug
(
"Tcp Socket configuración:"
);
Log
.
Debug
(
$" Blocking
{
tcpSocket
.
Blocking
}
"
);
Log
.
Debug
(
$" ExclusiveAddressUse
{
tcpSocket
.
ExclusiveAddressUse
}
"
);
...
...
@@ -140,7 +140,8 @@ public class ServidorGatewayCHEC(string ipGateway, int ptoGateway, string ipPOSB
((
IPEndPoint
)
clienteCHEC
.
RemoteEndPoint
).
Port
.
ToString
());
// Activa el POSBC
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
...
...
@@ -151,85 +152,144 @@ public class ServidorGatewayCHEC(string ipGateway, int ptoGateway, string ipPOSB
}
}
/// <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
)
public
void
ProcesarConexion
(
Socket
clienteCHEC
,
Socket
clientePOSBC
)
{
var
taskId
=
Task
.
CurrentId
?.
ToString
()
??
"no-task"
;
_socketCHEC
=
cliente
;
Log
.
Debug
(
"{tid} Tarea acepta entradas iniciada"
,
taskId
);
while
(
true
)
bool
continua
=
true
;
while
(
continua
)
{
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
);
var
bufferLongitud
=
new
byte
[
4
];
int
bytesLeidos
=
0
;
while
(
bytesLeidos
<
4
)
byte
[]
mensajeEntrada
=
Util
.
ConcatenaArreglosBytes
(
bufferLongitud
,
bufferEntrada
);
// Enviar mensaje de entrada a POSBC y retornar respuestas.
// 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.
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
)
catch
(
Exception
e
)
{
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
// la longitud del resto del mensaje.
//int nroBytesLeidos = await cliente.ReceiveAsync(new ArraySegment<byte>(bufferLongitud), SocketFlags.None);
// // ------------------- LECTURA SINCRONICA
// // 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.
// 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;
// }
// // ---------------------- LECTURA ASINCRONICA
// int longitudMensaje = Util.LongitudCodificada(bufferLongitud);
// Log.Debug("{tid} CHEC -> GTWY bytes cabecera {nroBytes}, longitud cuerpo mensaje {longitud}", taskId, nroBytesLeidos, longitudMensaje);
// // 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);
// // Lee los primeros 4 bytes de los datos de entrada, los cuales indican
// // la longitud del resto del mensaje.
// //int nroBytesLeidos = await cliente.ReceiveAsync(new ArraySegment<byte>(bufferLongitud), 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,
//
constituye el mensaje
.
string
mensaje
=
Encoding
.
UTF8
.
GetString
(
bufferEntrada
,
0
,
bytesLeidos
);
if
(
b
ytesLeidos
!
=
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
);
//
//
Si el número de bytes leidos es cero, la conexión se ha cerrado.
//
//
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 (nroB
ytesLeidos
=
=
0
)
//
//
{
//
//
Log.Warning("{tid}
CHEC -> GTWY emite 0 bytes - señal cierra conexión."
);
//
// break;
//
// }
// Se agrega mensaje a la cola de entrada de mensajes.
// await _canalEntrada.Writer.WriteAsync(mensaje);
// Log.Debug("{tid} mensaje {nro} -> [cola entrada]", taskId, _nroMsjEntrada);
// // int longitudMensaje = Util.LongitudCodificada(bufferLongitud);
// // Log.Debug("{tid} CHEC -> GTWY bytes cabecera {nroBytes}, longitud cuerpo mensaje {longitud}", taskId, nroBytesLeidos, longitudMensaje);
// // // 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.
string
mensajeProcesado
=
ProcesaMensajeCHEC
(
mensaje
);
await
_posbc
.
Envia
(
mensajeProcesado
);
}
cliente
.
Close
();
Log
.
Warning
(
"{tid} Tarea acepta entradas CHEC TERMINADA"
,
taskId
);
}
// _nroMsjEntradaCHEC++;
// Log.Information("{tid} CHEC -> GTWY nuevo mensaje #{nro} - cuerpo {bytes} bytes", taskId, _nroMsjEntradaCHEC, bytesLeidos);
// // Arreglo de bytes de entrada se transforma en string,
// // constituye el mensaje.
// 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>
/// Procesa los mensajes d entrada CHEC.
...
...
@@ -238,12 +298,12 @@ public class ServidorGatewayCHEC(string ipGateway, int ptoGateway, string ipPOSB
/// </summary>
/// <param name="mensaje"></param>
/// <returns></returns>
public
string
ProcesaMensajeCHEC
(
string
mensaje
)
{
Log
.
Debug
(
"GTWY procesador mensaje CHEC para POSBC invocado."
);
var
copiaMensaje
=
new
String
(
mensaje
);
return
copiaMensaje
;
}
//
public string ProcesaMensajeCHEC(string mensaje)
//
{
//
Log.Debug("GTWY procesador mensaje CHEC para POSBC invocado.");
//
var copiaMensaje = new String(mensaje);
//
return copiaMensaje;
//
}
/// <summary>
...
...
@@ -276,6 +336,31 @@ public class ServidorGatewayCHEC(string ipGateway, int ptoGateway, string ipPOSB
}
_nroMsjEntradaPOSBC
++;
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,
// constituye el mensaje.
...
...
@@ -287,7 +372,8 @@ public class ServidorGatewayCHEC(string ipGateway, int ptoGateway, string ipPOSB
if
(
mensajeProcesado
.
Length
>
0
)
{
byte
[]
bufferSalida
=
Util
.
ConvierteEnBufferBytes
(
mensajeProcesado
);
await
clienteCHEC
.
SendAsync
(
bufferSalida
);
//byte[] mensajeEntrada = Util.ConcatenaArreglosBytes(bufferLongitud, bufferEntrada);
await
clienteCHEC
.
SendAsync
(
bufferEntrada
);
_nroMsjSalidaCHEC
++;
Log
.
Information
(
"{tid} CHEC <- GTWY {nro} - {bytes} bytes total"
,
taskId
,
_nroMsjSalidaCHEC
,
bufferSalida
.
Length
);
Log
.
Verbose
(
"{tid} CHEC <- GTWY mensaje\n{msj}"
,
taskId
,
mensaje
);
...
...
Write
Preview
Supports
Markdown
0%
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment