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
a93e01b6
Commit
a93e01b6
authored
Jun 23, 2024
by
Jose Hugo Torres
Browse files
Servidor CHEC - sin cola de entrada
Mensajes que llegan de CHEC pasan directo a POSBC sin cola
parent
da7a2689
Changes
5
Hide whitespace changes
Inline
Side-by-side
gatewayGK/Infraestructura/Util.cs
View file @
a93e01b6
...
@@ -30,7 +30,7 @@ namespace GatewaySCO
...
@@ -30,7 +30,7 @@ namespace GatewaySCO
public
static
byte
[]
ConvierteEnBufferBytes
(
string
mensaje
)
public
static
byte
[]
ConvierteEnBufferBytes
(
string
mensaje
)
{
{
// Codifica longitud del mensaje en un entero sin signo en los 4 primeros bytes.
// Codifica longitud del mensaje en un entero sin signo en los 4 primeros bytes.
u
int
longitud
=
Convert
.
To
U
Int32
(
mensaje
.
Length
);
int
longitud
=
Convert
.
ToInt32
(
mensaje
.
Length
);
byte
[]
bytesConLongMensaje
=
BitConverter
.
GetBytes
(
longitud
);
byte
[]
bytesConLongMensaje
=
BitConverter
.
GetBytes
(
longitud
);
// Bytes mas significativos deben ir primero, usa 'big-endian'.
// Bytes mas significativos deben ir primero, usa 'big-endian'.
if
(
BitConverter
.
IsLittleEndian
)
if
(
BitConverter
.
IsLittleEndian
)
...
@@ -45,17 +45,18 @@ namespace GatewaySCO
...
@@ -45,17 +45,18 @@ namespace GatewaySCO
}
}
/// <summary>
/// <summary>
/// Longitud del mensaje, retorna entero sin signo representado en los 4 primeros bytes del parámetro.
/// Longitud del mensaje, retorna entero representado en los 4 primeros bytes
/// del arreglo de bytes del parámetro, que corresponde a un mensaje codificado en bytes.
/// </summary>
/// </summary>
public
static
u
int
Longitud
Mensaje
(
byte
[]
bytesMensaje
)
public
static
int
Longitud
Codificada
(
byte
[]
bytesMensaje
)
{
{
// Extrae longitud. Primeros 4 bytes del arreglo.
// Extrae longitud. Primeros 4 bytes del arreglo.
byte
[]
bytesLongitudMensaje
=
new
byte
[
4
];
byte
[]
bytesLongitudMensaje
=
new
byte
[
4
];
Buffer
.
BlockCopy
(
bytesMensaje
,
0
,
bytesLongitudMensaje
,
0
,
4
);
Buffer
.
BlockCopy
(
bytesMensaje
,
0
,
bytesLongitudMensaje
,
0
,
4
);
if
(
BitConverter
.
IsLittleEndian
)
if
(
BitConverter
.
IsLittleEndian
)
Array
.
Reverse
(
bytesLongitudMensaje
);
Array
.
Reverse
(
bytesLongitudMensaje
);
u
int
enteroSinSigno
=
BitConverter
.
To
U
Int32
(
bytesLongitudMensaje
,
0
);
int
longitud
=
BitConverter
.
ToInt32
(
bytesLongitudMensaje
,
0
);
return
enteroSinSigno
;
return
longitud
;
}
}
/// <summary>
/// <summary>
...
@@ -110,7 +111,7 @@ namespace GatewaySCO
...
@@ -110,7 +111,7 @@ namespace GatewaySCO
while
(
continua
)
while
(
continua
)
{
{
// Extrae longitud.
// Extrae longitud.
int
longitud
=
Convert
.
ToInt32
(
LongitudMensaje
(
buffer
)
)
;
int
longitud
=
LongitudCodificada
(
buffer
);
contenido
.
Append
(
$"\n\tlongitud:
{
longitud
}
"
);
contenido
.
Append
(
$"\n\tlongitud:
{
longitud
}
"
);
if
(
longitud
+
puntero
>
buffer
.
Length
)
if
(
longitud
+
puntero
>
buffer
.
Length
)
{
{
...
...
gatewayGK/POSBC/ClienteServidorPOSBC.cs
View file @
a93e01b6
...
@@ -16,7 +16,7 @@ public class ClienteServidorPOSBC(string ip, int pto)
...
@@ -16,7 +16,7 @@ public class ClienteServidorPOSBC(string ip, int pto)
private
static
Socket
_socket
=
null
;
private
static
Socket
_socket
=
null
;
public
bool
ConexionActiva
{
get
;
private
set
;
}
=
false
;
public
bool
ConexionActiva
{
get
;
private
set
;
}
=
false
;
private
int
_nroMsjEnviados
=
0
;
private
int
_nroMsjEnviados
=
0
;
private
int
_nroMsjRecibidos
=
0
;
private
int
_nroMsjRecibidos
;
public
void
AbreConexion
()
public
void
AbreConexion
()
{
{
...
@@ -66,8 +66,8 @@ public class ClienteServidorPOSBC(string ip, int pto)
...
@@ -66,8 +66,8 @@ public class ClienteServidorPOSBC(string ip, int pto)
byte
[]
buffer
=
Util
.
ConvierteEnBufferBytes
(
msj
);
byte
[]
buffer
=
Util
.
ConvierteEnBufferBytes
(
msj
);
await
_socket
.
SendAsync
(
buffer
);
await
_socket
.
SendAsync
(
buffer
);
_nroMsjEnviados
++;
_nroMsjEnviados
++;
Log
.
Information
(
"{tid} G
ateway
-> POSBC {nro} - {bytes} bytes total"
,
taskId
,
_nroMsjEnviados
,
buffer
.
Length
);
Log
.
Information
(
"{tid} G
TWY
-> POSBC {nro} - {bytes} bytes total"
,
taskId
,
_nroMsjEnviados
,
buffer
.
Length
);
Log
.
Verbose
(
"{tid} G
ateway
-> POSBC mensaje\n{msj}"
,
taskId
,
msj
);
Log
.
Verbose
(
"{tid} G
TWY
-> POSBC mensaje\n{msj}"
,
taskId
,
msj
);
}
}
public
async
Task
Recibe
(
Channel
<
string
>
canalSalida
)
public
async
Task
Recibe
(
Channel
<
string
>
canalSalida
)
...
@@ -89,21 +89,20 @@ public class ClienteServidorPOSBC(string ip, int pto)
...
@@ -89,21 +89,20 @@ public class ClienteServidorPOSBC(string ip, int pto)
// Mientras tenga conexión, se queda esperando datos.
// Mientras tenga conexión, se queda esperando datos.
if
(
nroBytesLeidos
==
0
)
break
;
if
(
nroBytesLeidos
==
0
)
break
;
uint
longitudMensaje
=
Util
.
LongitudMensaje
(
bufferLongitud
);
int
longitudMensaje
=
Util
.
LongitudCodificada
(
bufferLongitud
);
int
lMensaje
=
Convert
.
ToInt32
(
longitudMensaje
);
Log
.
Debug
(
"{tid} POSBC bytes cabecera {nroBytes}, longitud mensaje {longitud}"
,
taskId
,
nroBytesLeidos
,
longitudMensaje
);
Log
.
Debug
(
"{tid} POSBC bytes cabecera {nroBytes}, longitud mensaje {longitud} uint {uint}"
,
taskId
,
nroBytesLeidos
,
lMensaje
,
longitudMensaje
);
// Prepara buffer de entrada según la longitud esperada del mensaje.
// Prepara buffer de entrada según la longitud esperada del mensaje.
var
bufferMensaje
=
new
byte
[
longitudMensaje
];
var
bufferMensaje
=
new
byte
[
longitudMensaje
];
nroBytesLeidos
=
await
_socket
.
ReceiveAsync
(
new
ArraySegment
<
byte
>(
bufferMensaje
),
SocketFlags
.
None
);
nroBytesLeidos
=
await
_socket
.
ReceiveAsync
(
new
ArraySegment
<
byte
>(
bufferMensaje
),
SocketFlags
.
None
);
Log
.
Debug
(
"{tid} POSBC bytes mensaje {nroBytes}"
,
taskId
,
nroBytesLeidos
);
Log
.
Debug
(
"{tid} POSBC bytes mensaje {nroBytes}"
,
taskId
,
nroBytesLeidos
);
_nroMsjRecibidos
++;
_nroMsjRecibidos
++;
Log
.
Information
(
"{tid} G
ateway
<- POSBC {nro} - {bytes} bytes cuerpo"
,
taskId
,
_nroMsjRecibidos
,
nroBytesLeidos
);
Log
.
Information
(
"{tid} G
TWY
<- POSBC {nro} - {bytes} bytes cuerpo"
,
taskId
,
_nroMsjRecibidos
,
nroBytesLeidos
);
// Arreglo de bytes de entrada se transforma en string,
// Arreglo de bytes de entrada se transforma en string,
// constituye el mensaje.
// constituye el mensaje.
string
mensaje
=
Encoding
.
UTF8
.
GetString
(
bufferMensaje
,
0
,
nroBytesLeidos
);
string
mensaje
=
Encoding
.
UTF8
.
GetString
(
bufferMensaje
,
0
,
nroBytesLeidos
);
Log
.
Verbose
(
"{tid} G
ateway
<- POSBC mensaje\n{msj}"
,
taskId
,
mensaje
);
Log
.
Verbose
(
"{tid} G
TWY
<- POSBC mensaje\n{msj}"
,
taskId
,
mensaje
);
// Se agrega mensaje a la cola de entrada de mensajes.
// Se agrega mensaje a la cola de entrada de mensajes.
await
canalSalida
.
Writer
.
WriteAsync
(
mensaje
);
await
canalSalida
.
Writer
.
WriteAsync
(
mensaje
);
...
...
gatewayGK/Servidor/EvaPosSrvSCO.cs
View file @
a93e01b6
...
@@ -276,7 +276,7 @@ namespace EvaPosSCOSrv
...
@@ -276,7 +276,7 @@ namespace EvaPosSCOSrv
Log
.
Debug
(
"Arriba un mensaje."
);
Log
.
Debug
(
"Arriba un mensaje."
);
// Lee porción de datos del mensaje, hasta la longitud indicada en los 4 primeros bytes.
// Lee porción de datos del mensaje, hasta la longitud indicada en los 4 primeros bytes.
u
int
longitudMensaje
=
Util
.
Longitud
Mensaje
(
bufferLongitud
);
int
longitudMensaje
=
Util
.
Longitud
Codificada
(
bufferLongitud
);
if
(
longitudMensaje
>
LongMaxMensaje
)
throw
new
Exception
(
$"Mensaje
{
longitudMensaje
}
bytes supera máximo permitido de
{
LongMaxMensaje
}
bytes."
);
if
(
longitudMensaje
>
LongMaxMensaje
)
throw
new
Exception
(
$"Mensaje
{
longitudMensaje
}
bytes supera máximo permitido de
{
LongMaxMensaje
}
bytes."
);
var
bufferEntrada
=
new
byte
[
longitudMensaje
];
var
bufferEntrada
=
new
byte
[
longitudMensaje
];
bytesLeidos
=
0
;
bytesLeidos
=
0
;
...
...
gatewayGK/Servidor/GatewayCHEC.cs
View file @
a93e01b6
...
@@ -111,7 +111,7 @@ public class ServidorGatewayCHEC(string ipGateway, int ptoGateway, string ipPOSB
...
@@ -111,7 +111,7 @@ public class ServidorGatewayCHEC(string ipGateway, int ptoGateway, string ipPOSB
Log
.
Information
(
"Gateway servidor socket en {ip} : {puerto}, proceso id {id}"
,
IpGateway
,
PuertoGateway
,
idProceso
);
Log
.
Information
(
"Gateway servidor socket en {ip} : {puerto}, proceso id {id}"
,
IpGateway
,
PuertoGateway
,
idProceso
);
if
(
_isDebug
)
if
(
_isDebug
)
{
{
Log
.
Debug
(
"Versión framework {version} #
6
"
,
Environment
.
Version
);
Log
.
Debug
(
"Versión framework {version} #
10
"
,
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
}
"
);
...
@@ -128,7 +128,7 @@ public class ServidorGatewayCHEC(string ipGateway, int ptoGateway, string ipPOSB
...
@@ -128,7 +128,7 @@ public class ServidorGatewayCHEC(string ipGateway, int ptoGateway, string ipPOSB
{
{
// Activa el POSBC
// Activa el POSBC
if
(
_posbc
==
null
)
ActivaPOSBC
();
if
(
_posbc
==
null
)
ActivaPOSBC
();
var
tareaProcesaMsj
=
Task
.
Run
(()
=>
ProcesaEntradaCHEC
());
//
var tareaProcesaMsj = Task.Run(() => ProcesaEntradaCHEC());
var
tareaRecibePOSBC
=
Task
.
Run
(()
=>
_posbc
.
Recibe
(
_canalSalida
));
var
tareaRecibePOSBC
=
Task
.
Run
(()
=>
_posbc
.
Recibe
(
_canalSalida
));
var
tareaRemiteRespuesta
=
Task
.
Run
(()
=>
ProcesaSalidaPOSBC
());
var
tareaRemiteRespuesta
=
Task
.
Run
(()
=>
ProcesaSalidaPOSBC
());
...
@@ -155,39 +155,74 @@ public class ServidorGatewayCHEC(string ipGateway, int ptoGateway, string ipPOSB
...
@@ -155,39 +155,74 @@ public class ServidorGatewayCHEC(string ipGateway, int ptoGateway, string ipPOSB
Log
.
Debug
(
"{tid} Tarea acepta entradas iniciada"
,
taskId
);
Log
.
Debug
(
"{tid} Tarea acepta entradas iniciada"
,
taskId
);
while
(
true
)
while
(
true
)
{
{
// ------------------- LECTURA SINCRONICA
// Lee longitud mensaje entrante, 4 bytes.
// Lee longitud mensaje entrante, 4 bytes.
Log
.
Information
(
"{tid} Esperando CHEC"
,
taskId
);
Log
.
Information
(
"{tid} Esperando CHEC"
,
taskId
);
var
bufferLongitud
=
new
byte
[
4
];
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
);
}
// ---------------------- LECTURA ASINCRONICA
// Lee los primeros 4 bytes de los datos de entrada, los cuales indican
// Lee los primeros 4 bytes de los datos de entrada, los cuales indican
// la longitud del resto del mensaje.
// la longitud del resto del mensaje.
int
nroBytesLeidos
=
await
cliente
.
ReceiveAsync
(
new
ArraySegment
<
byte
>(
bufferLongitud
),
SocketFlags
.
None
);
//int nroBytesLeidos = await cliente.ReceiveAsync(new ArraySegment<byte>(bufferLongitud), SocketFlags.None);
// Si el número de bytes leidos es cero, la conexión se ha cerrado.
// 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.
// 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.
// Mientras tenga conexión, se queda esperando datos.
if
(
nroBytesLeidos
==
0
)
break
;
// if (nroBytesLeidos == 0)
// {
uint
longitudMensaje
=
Util
.
LongitudMensaje
(
bufferLongitud
);
// Log.Warning("{tid} CHEC -> GTWY emite 0 bytes - señal cierra conexión.");
Log
.
Debug
(
"{tid} CHECK bytes cabecera {nroBytes}, longitud mensaje {longitud}"
,
taskId
,
nroBytesLeidos
,
longitudMensaje
);
// break;
// Prepara buffer de entrada según la longitud esperada del mensaje.
// }
var
bufferMensaje
=
new
byte
[
longitudMensaje
];
//nroBytesLeidos = cliente.Receive(bufferMensaje, 0, bufferMensaje.Length, SocketFlags.None);
// int longitudMensaje = Util.LongitudCodificada(bufferLongitud);
nroBytesLeidos
=
await
cliente
.
ReceiveAsync
(
new
ArraySegment
<
byte
>(
bufferMensaje
),
SocketFlags
.
None
);
// Log.Debug("{tid} CHEC -> GTWY bytes cabecera {nroBytes}, longitud cuerpo mensaje {longitud}", taskId, nroBytesLeidos, longitudMensaje);
Log
.
Debug
(
"{tid} CHECK bytes mensaje {nroBytes}"
,
taskId
,
nroBytesLeidos
);
// // 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);
_nroMsjEntrada
++;
_nroMsjEntrada
++;
Log
.
Information
(
"{tid} CHEC -> G
ateway
{nro} - {bytes} bytes
cuerpo
"
,
taskId
,
_nroMsjEntrada
,
nroB
ytesLeidos
);
Log
.
Information
(
"{tid} CHEC -> G
TWY nuevo mensaje #
{nro} -
cuerpo
{bytes} bytes"
,
taskId
,
_nroMsjEntrada
,
b
ytesLeidos
);
// Arreglo de bytes de entrada se transforma en string,
// Arreglo de bytes de entrada se transforma en string,
// constituye el mensaje.
// constituye el mensaje.
string
mensaje
=
Encoding
.
UTF8
.
GetString
(
bufferMensaje
,
0
,
nroBytesLeidos
);
string
mensaje
=
Encoding
.
UTF8
.
GetString
(
bufferEntrada
,
0
,
bytesLeidos
);
Log
.
Verbose
(
"{tid} CHEC -> Gateway mensaje\n{msj}"
,
taskId
,
mensaje
);
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.
// Se agrega mensaje a la cola de entrada de mensajes.
await
_canalEntrada
.
Writer
.
WriteAsync
(
mensaje
);
// await _canalEntrada.Writer.WriteAsync(mensaje);
Log
.
Debug
(
"{tid} mensaje -> [cola entrada]"
,
taskId
);
// Log.Debug("{tid} mensaje {nro} -> [cola entrada]", taskId, _nroMsjEntrada);
//
//
// PROCESA EL MENSAJE CHEC -> GATEWAY
//
//
await
_posbc
.
Envia
(
mensaje
);
}
}
cliente
.
Close
();
cliente
.
Close
();
Log
.
Warning
(
"{tid} CHEC conexión cerrada"
,
taskId
);
}
}
private
static
async
Task
ProcesaEntradaCHEC
()
private
static
async
Task
ProcesaEntradaCHEC
()
...
@@ -225,8 +260,8 @@ public class ServidorGatewayCHEC(string ipGateway, int ptoGateway, string ipPOSB
...
@@ -225,8 +260,8 @@ public class ServidorGatewayCHEC(string ipGateway, int ptoGateway, string ipPOSB
byte
[]
bufferSalida
=
Util
.
ConvierteEnBufferBytes
(
mensaje
);
byte
[]
bufferSalida
=
Util
.
ConvierteEnBufferBytes
(
mensaje
);
await
_socketCHEC
.
SendAsync
(
bufferSalida
);
await
_socketCHEC
.
SendAsync
(
bufferSalida
);
_nroMsjSalida
++;
_nroMsjSalida
++;
Log
.
Information
(
"{tid} CHEC <- G
ateway
{nro} - {bytes} bytes total"
,
taskId
,
_nroMsjSalida
,
bufferSalida
.
Length
);
Log
.
Information
(
"{tid} CHEC <- G
TWY
{nro} - {bytes} bytes total"
,
taskId
,
_nroMsjSalida
,
bufferSalida
.
Length
);
Log
.
Verbose
(
"{tid} CHEC <- G
ateway
mensaje\n{msj}"
,
taskId
,
mensaje
);
Log
.
Verbose
(
"{tid} CHEC <- G
TWY
mensaje\n{msj}"
,
taskId
,
mensaje
);
}
}
}
}
}
}
\ No newline at end of file
gatewayPruebaECO/ProgramECO.cs
View file @
a93e01b6
...
@@ -165,7 +165,8 @@ public class SocketClientECO
...
@@ -165,7 +165,8 @@ public class SocketClientECO
byte
[]
bufferMsj
=
Util
.
ConvierteEnBufferBytes
(
message
);
byte
[]
bufferMsj
=
Util
.
ConvierteEnBufferBytes
(
message
);
await
socket
.
SendAsync
(
new
ArraySegment
<
byte
>(
bufferMsj
),
SocketFlags
.
None
);
await
socket
.
SendAsync
(
new
ArraySegment
<
byte
>(
bufferMsj
),
SocketFlags
.
None
);
Console
.
WriteLine
(
$"Mensaje enviado:
{
message
}
"
);
Console
.
WriteLine
(
$"Mensaje enviado:
{
message
}
espera 1 segundo"
);
Task
.
Delay
(
1000
).
Wait
();
}
}
// Recibir mensajes de forma asincrónica en un ciclo infinito
// Recibir mensajes de forma asincrónica en un ciclo infinito
...
...
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