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
41a876af
Commit
41a876af
authored
Jun 24, 2024
by
Jose Hugo Torres
Browse files
Servidor B
TCPListener
parent
191cdc3f
Changes
9
Show whitespace changes
Inline
Side-by-side
CHECPrueba/CHECPrueba.csproj
0 → 100644
View file @
41a876af
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\gatewayGK\gatewayGK.csproj" />
</ItemGroup>
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
CHECPrueba/Program.cs
0 → 100644
View file @
41a876af
using
System.Net.Sockets
;
using
System.Text
;
using
GatewaySCO
;
using
Serilog
;
public
class
CHECPrueba
{
private
const
string
GatewayServer
=
"127.0.0.1"
;
private
const
int
GatewayPort
=
6697
;
public
static
async
Task
Main
(
string
[]
args
)
{
Log
.
Logger
=
new
LoggerConfiguration
()
.
WriteTo
.
Console
()
.
CreateLogger
();
try
{
using
TcpClient
client
=
new
TcpClient
();
await
client
.
ConnectAsync
(
GatewayServer
,
GatewayPort
);
Log
.
Information
(
"Conectado al Gateway."
);
using
NetworkStream
stream
=
client
.
GetStream
();
int
messageNumber
=
1
;
while
(
true
)
{
// Remitir un mensaje numerado al Gateway
string
message
=
$"Mensaje
{
messageNumber
}
desde CHEC"
;
byte
[]
messageBytes
=
Encoding
.
UTF8
.
GetBytes
(
message
);
byte
[]
lengthBytes
=
BitConverter
.
GetBytes
(
messageBytes
.
Length
);
if
(
BitConverter
.
IsLittleEndian
)
{
Array
.
Reverse
(
lengthBytes
);
}
byte
[]
bytesMsj
=
Util
.
ConcatenaArreglosBytes
(
lengthBytes
,
messageBytes
);
// await stream.WriteAsync(lengthBytes, 0, 4);
// await stream.WriteAsync(messageBytes, 0, messageBytes.Length);
await
stream
.
WriteAsync
(
bytesMsj
,
0
,
bytesMsj
.
Length
);
Log
.
Information
(
$"Mensaje
{
messageNumber
}
enviado al Gateway:
{
message
}
"
);
// Esperar por una o más respuestas
await
ReceiveResponsesAsync
(
stream
);
messageNumber
++;
await
Task
.
Delay
(
5000
);
// Esperar 5 segundos antes de enviar el siguiente mensaje
}
}
catch
(
Exception
ex
)
{
Log
.
Error
(
ex
,
"Error en CHECPrueba"
);
}
finally
{
Log
.
CloseAndFlush
();
}
}
private
static
async
Task
ReceiveResponsesAsync
(
NetworkStream
stream
)
{
byte
[]
lengthBuffer
=
new
byte
[
4
];
while
(
stream
.
DataAvailable
)
{
// Leer longitud del mensaje de respuesta
int
bytesRead
=
await
stream
.
ReadAsync
(
lengthBuffer
,
0
,
4
);
if
(
bytesRead
==
0
)
break
;
// La conexión se ha cerrado
if
(
BitConverter
.
IsLittleEndian
)
{
Array
.
Reverse
(
lengthBuffer
);
}
int
messageLength
=
BitConverter
.
ToInt32
(
lengthBuffer
,
0
);
byte
[]
messageBuffer
=
new
byte
[
messageLength
];
bytesRead
=
await
stream
.
ReadAsync
(
messageBuffer
,
0
,
messageLength
);
if
(
bytesRead
==
0
)
continue
;
// La conexión se ha cerrado
string
response
=
Encoding
.
UTF8
.
GetString
(
messageBuffer
,
0
,
bytesRead
);
Log
.
Information
(
$"Respuesta recibida:
{
response
}
"
);
}
}
}
POSBCPrueba/POSBCPrueba.csproj
0 → 100644
View file @
41a876af
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\gatewayGK\gatewayGK.csproj" />
</ItemGroup>
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
POSBCPrueba/Program.cs
0 → 100644
View file @
41a876af
using
System.Net
;
using
System.Net.Sockets
;
using
System.Text
;
using
GatewaySCO
;
using
Serilog
;
public
class
PosbcServer
{
private
const
int
Port
=
6698
;
private
static
int
messageCounter
=
1
;
public
static
async
Task
Main
()
{
Log
.
Logger
=
new
LoggerConfiguration
()
.
WriteTo
.
Console
()
.
CreateLogger
();
try
{
TcpListener
listener
=
new
TcpListener
(
IPAddress
.
Any
,
Port
);
listener
.
Start
();
Log
.
Information
(
$"POSBC escuchando en el puerto
{
Port
}
..."
);
while
(
true
)
{
TcpClient
gatewayClient
=
await
listener
.
AcceptTcpClientAsync
();
Log
.
Information
(
"Gateway conectado."
);
_
=
Task
.
Run
(()
=>
HandleGatewayClientAsync
(
gatewayClient
));
}
}
catch
(
Exception
ex
)
{
Log
.
Error
(
ex
,
"Error en el servidor POSBC"
);
}
finally
{
Log
.
CloseAndFlush
();
}
}
private
static
async
Task
HandleGatewayClientAsync
(
TcpClient
gatewayClient
)
{
using
(
gatewayClient
)
using
(
NetworkStream
stream
=
gatewayClient
.
GetStream
())
{
byte
[]
buffer
=
new
byte
[
4096
];
while
(
true
)
{
// Leer longitud del mensaje desde Gateway
byte
[]
lengthBuffer
=
new
byte
[
4
];
int
bytesRead
=
await
stream
.
ReadAsync
(
lengthBuffer
,
0
,
4
);
if
(
bytesRead
==
0
)
continue
;
// Si no se lee nada, continuar esperando
if
(
BitConverter
.
IsLittleEndian
)
{
Array
.
Reverse
(
lengthBuffer
);
}
int
messageLength
=
BitConverter
.
ToInt32
(
lengthBuffer
,
0
);
byte
[]
messageBuffer
=
new
byte
[
messageLength
];
bytesRead
=
await
stream
.
ReadAsync
(
messageBuffer
,
0
,
messageLength
);
if
(
bytesRead
==
0
)
continue
;
// Si no se lee nada, continuar esperando
string
message
=
Encoding
.
UTF8
.
GetString
(
messageBuffer
,
0
,
bytesRead
);
Log
.
Information
(
$"Mensaje recibido del Gateway:
{
message
}
"
);
// Esperar 2 segundos antes de enviar la primera respuesta
await
Task
.
Delay
(
2000
);
await
EnviarMensaje
(
stream
,
$"Respuesta
{
messageCounter
++}
desde POSBC"
);
// Esperar 2 segundos y enviar dos mensajes adicionales
await
Task
.
Delay
(
2000
);
await
EnviarMensaje
(
stream
,
$"Mensaje adicional
{
messageCounter
++}
desde POSBC"
);
await
Task
.
Delay
(
2000
);
await
EnviarMensaje
(
stream
,
$"Mensaje adicional
{
messageCounter
++}
desde POSBC"
);
}
}
}
private
static
async
Task
EnviarMensaje
(
NetworkStream
stream
,
string
mensaje
)
{
byte
[]
messageBytes
=
Encoding
.
UTF8
.
GetBytes
(
mensaje
);
byte
[]
lengthBytes
=
BitConverter
.
GetBytes
(
messageBytes
.
Length
);
if
(
BitConverter
.
IsLittleEndian
)
{
Array
.
Reverse
(
lengthBytes
);
}
byte
[]
bytesMsj
=
Util
.
ConcatenaArreglosBytes
(
lengthBytes
,
messageBytes
);
// await stream.WriteAsync(lengthBytes, 0, 4);
// await stream.WriteAsync(messageBytes, 0, messageBytes.Length);
await
stream
.
WriteAsync
(
bytesMsj
);
Log
.
Information
(
$"Mensaje enviado al Gateway:
{
mensaje
}
"
);
}
}
gatewayGK.sln
View file @
41a876af
...
...
@@ -9,6 +9,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "gatewayPruebaECO", "gateway
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "gatewayPruebaECO_POSBC", "gatewayPruebaECO_POSBC\gatewayPruebaECO_POSBC.csproj", "{4A774AA8-BB85-4836-A011-D99952744E2B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CHECPrueba", "CHECPrueba\CHECPrueba.csproj", "{E4D08974-7DD1-4C32-A340-149FED62A437}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "POSBCPrueba", "POSBCPrueba\POSBCPrueba.csproj", "{C0A995FB-66EC-43A4-9C6D-1FF0BA25F00F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
...
...
@@ -27,6 +31,14 @@ Global
{4A774AA8-BB85-4836-A011-D99952744E2B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4A774AA8-BB85-4836-A011-D99952744E2B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4A774AA8-BB85-4836-A011-D99952744E2B}.Release|Any CPU.Build.0 = Release|Any CPU
{E4D08974-7DD1-4C32-A340-149FED62A437}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E4D08974-7DD1-4C32-A340-149FED62A437}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E4D08974-7DD1-4C32-A340-149FED62A437}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E4D08974-7DD1-4C32-A340-149FED62A437}.Release|Any CPU.Build.0 = Release|Any CPU
{C0A995FB-66EC-43A4-9C6D-1FF0BA25F00F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C0A995FB-66EC-43A4-9C6D-1FF0BA25F00F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C0A995FB-66EC-43A4-9C6D-1FF0BA25F00F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C0A995FB-66EC-43A4-9C6D-1FF0BA25F00F}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
...
...
gatewayGK/Program.cs
View file @
41a876af
...
...
@@ -7,35 +7,29 @@ using EvaPosSrvAplicacionImp;
using
EvaPosSrvRespImp
;
using
gatewaySCO.POSBC
;
using
GatewayCHEC.Servidor
;
using
Servidor.TcpGatewayB
;
namespace
GatewaySCO
{
public
class
TaskIdEnricher
:
ILogEventEnricher
{
public
const
string
TaskIdPropertyName
=
"TaskId"
;
public
void
Enrich
(
LogEvent
logEvent
,
ILogEventPropertyFactory
propertyFactory
)
{
var
taskId
=
Task
.
CurrentId
?.
ToString
()
??
"no-task"
;
logEvent
.
AddPropertyIfAbsent
(
propertyFactory
.
CreateProperty
(
TaskIdPropertyName
,
taskId
));
}
}
/// <summary>
/// EvaPos-API : servidor api, sockets y rest.
/// Usa Serilog para bitácora.
/// </summary>
public
class
ProgramGatewaySCO
{
static
void
Main
(
string
[]
args
)
public
static
void
Hola
(
string
[]
args
)
{
Console
.
WriteLine
(
"*** Gateway SCO - Servidor: procesa peticiones de Toshiba CHEC ***"
);
ProgramGatewaySCO
program
=
new
();
LeeActivaConfiguracion
(
args
);
program
.
LeeActivaConfiguracion
(
args
);
TcpGatewayB
gateway
=
new
TcpGatewayB
();
//await gateway.Start();
}
public
static
void
LeeActivaConfiguracion
(
string
[]
args
)
public
void
LeeActivaConfiguracion
(
string
[]
args
)
{
// TODO - opción de incluir la activación en la cadena de configuración.
...
...
@@ -58,119 +52,7 @@ namespace GatewaySCO
Config
config
=
configBuilder
.
GetRequiredSection
(
"GatewayConfig"
).
Get
<
Config
>()
??
throw
new
ApplicationException
(
"Archivo de configuración sin sección 'GatewayConfig'."
);
Log
.
Information
(
config
.
ToString
());
Entorno
<
Config
>.
Instancia
.
set
(
config
);
// // Lee del archivo de configuración sección POS Gk si aplica.
// // TODO - valor de parámetro POS de archivo de configuración en ENUM?
// if (config.POS == "gk")
// {
// ConfigGk configGk = configBuilder.GetRequiredSection("DataGK").Get<ConfigGk>()
// ?? throw new ApplicationException("Archivo de configuración sin sección 'DataGK'.");
// Log.Debug(configGk.ToString());
// // Inicializa el entorno Gk.
// Entorno<EntornoGK>.Instancia.set(new EntornoGK());
// Entorno<EntornoGK>.Instancia.get().Language = config.Language;
// Entorno<EntornoGK>.Instancia.get().ConfigGk = configGk;
// Log.Information($"GK {Entorno<EntornoGK>.Instancia.get().UrlBase}");
// }
// // Configuración para pruebas de emulación del POSBC.
// if (config.POS == "ECO_POSBC")
// {
// ConfigPOSBC configPOSBC = configBuilder.GetRequiredSection("POSBC").Get<ConfigPOSBC>()
// ?? throw new ApplicationException("Archivo de configuración sin sección 'POSBC'.");
// Log.Information(configPOSBC.ToString());
// Entorno<EntornoPOSBC>.Instancia.set(new EntornoPOSBC());
// Entorno<EntornoPOSBC>.Instancia.get().IpPOSBC = configPOSBC.IpPOSBC;
// Entorno<EntornoPOSBC>.Instancia.get().PortPOSBC = configPOSBC.PortPOSBC;
// // Se activa lógica de cliente POSBC
// // La conexión con el POSBC se almacena en el entorno para uso
// // posterior en la emisión y recepción de mensajes.
// Entorno<EntornoPOSBC>.Instancia.get().ClientePOSBC = new ClienteServidorPOSBC(configPOSBC.IpPOSBC, configPOSBC.PortPOSBC);
// Entorno<EntornoPOSBC>.Instancia.get().ClientePOSBC.AbreConexion();
// if (Entorno<EntornoPOSBC>.Instancia.get().ClientePOSBC.ConexionActiva == false)
// {
// throw new ApplicationException("Error en conexión al POSBC.");
// }
// }
// Activa servidor Gateway.
// En este punto, el programa se bloquea esperando conexión y mensajes desde CHEC.
switch
(
config
.
POS
)
{
case
"gk"
:
{
// Procesa sección DataGK del archivo de configuración.
ConfigGk
configGk
=
configBuilder
.
GetRequiredSection
(
"DataGK"
).
Get
<
ConfigGk
>()
??
throw
new
ApplicationException
(
"Archivo de configuración sin sección 'DataGK'."
);
Log
.
Debug
(
configGk
.
ToString
());
// Inicializa el entorno Gk.
Entorno
<
EntornoGK
>.
Instancia
.
set
(
new
EntornoGK
());
Entorno
<
EntornoGK
>.
Instancia
.
get
().
Language
=
config
.
Language
;
Entorno
<
EntornoGK
>.
Instancia
.
get
().
ConfigGk
=
configGk
;
Log
.
Information
(
$"GK
{
Entorno
<
EntornoGK
>.
Instancia
.
get
().
UrlBase
}
"
);
break
;
}
case
"ECO_POSBC"
:
{
// Procesa sección POSBC del archivo de configuración.
ConfigPOSBC
configPOSBC
=
configBuilder
.
GetRequiredSection
(
"POSBC"
).
Get
<
ConfigPOSBC
>()
??
throw
new
ApplicationException
(
"Archivo de configuración sin sección 'POSBC'."
);
Log
.
Information
(
configPOSBC
.
ToString
());
Entorno
<
EntornoPOSBC
>.
Instancia
.
set
(
new
EntornoPOSBC
());
Entorno
<
EntornoPOSBC
>.
Instancia
.
get
().
IpPOSBC
=
configPOSBC
.
IpPOSBC
;
Entorno
<
EntornoPOSBC
>.
Instancia
.
get
().
PortPOSBC
=
configPOSBC
.
PortPOSBC
;
// Activa cliente de conexión a POSBC. La conexión con el POSBC
// se almacena en el entorno para uso posterior en la emisión y recepción de mensajes.
//Entorno<EntornoPOSBC>.Instancia.get().ClientePOSBC = new ClienteServidorPOSBC(configPOSBC.IpPOSBC, configPOSBC.PortPOSBC);
//Entorno<EntornoPOSBC>.Instancia.get().ClientePOSBC.AbreConexion();
// if (Entorno<EntornoPOSBC>.Instancia.get().ClientePOSBC.ConexionActiva == false)
// {
// throw new ApplicationException("Error en conexión al POSBC.");
// }
break
;
}
default
:
{
throw
new
ApplicationException
(
$"Configuración POS desconocida:
{
config
.
POS
}
"
);
}
}
//ActivaServidor(config.IpGateway, config.PortGateway, config.POS);
// Activa servidor Gateway.
try
{
string
ipPOSBC
=
Entorno
<
EntornoPOSBC
>.
Instancia
.
get
().
IpPOSBC
;
int
ptoPOSBC
=
Entorno
<
EntornoPOSBC
>.
Instancia
.
get
().
PortPOSBC
;
ServidorGatewayCHEC
gateway
=
new
(
config
.
IpGateway
,
config
.
PortGateway
,
ipPOSBC
,
ptoPOSBC
);
gateway
.
Activa
();
}
catch
(
Exception
e
)
{
Log
.
Error
(
"Excepción {e}"
,
e
.
ToString
);
Environment
.
Exit
(
1
);
}
}
// Servidor sockets: acepta peticiones de SCO CHEC.
public
static
void
ActivaServidor
(
string
ip
,
int
pto
,
string
tipoPOS
)
{
try
{
// TODO - aunque hace uso de una "invocación fluida" no parece ser el tipo de api que se beneficia de ese esquema.
ServidorSocket
servidor
=
new
ServidorSocket
()
.
ConIp
(
ip
)
.
EnPuerto
(
pto
)
.
AgregaDispensadorAdaptadores
(
IniciaDirectorioAdaptadores
.
Cargar
().
DirectorioAdaptadores
)
.
AgregaDirectorioCmds
(
DirectorioCmdsFactory
.
CreaDirectorio
(
tipoPOS
))
.
AgregaProcesadorAplicacion
(
new
Aplicacion
())
.
Activa
();
}
catch
(
Exception
e
)
{
Log
.
Error
(
$"Excepción:
{
e
}
"
);
Environment
.
Exit
(
1
);
}
}
}
}
gatewayGK/Servidor/TcpGatewayA.cs
0 → 100644
View file @
41a876af
using
System
;
using
System.Net
;
using
System.Net.Sockets
;
using
System.Text
;
using
System.Threading.Tasks
;
namespace
Servidor.TcpGatewayA
;
/******************************************************************************
SERVIDOR CIERRA LA CONEXIÓN CHEC LUEGO DEL PRIMER MENSAJE, ESPERANDO QUE
CHEC SE CONECTE NUEVAMENTE.
*/
public
class
TcpGateway
{
private
const
int
GatewayPort
=
6697
;
private
const
string
PosbcServer
=
"127.0.0.1"
;
private
const
int
PosbcPort
=
6698
;
public
static
async
Task
Main
()
{
TcpListener
gatewayListener
=
new
TcpListener
(
IPAddress
.
Any
,
GatewayPort
);
gatewayListener
.
Start
();
Console
.
WriteLine
(
$"Gateway escuchando en el puerto
{
GatewayPort
}
..."
);
while
(
true
)
{
TcpClient
checClient
=
await
gatewayListener
.
AcceptTcpClientAsync
();
Console
.
WriteLine
(
"CHEC conectado."
);
_
=
Task
.
Run
(()
=>
HandleChecClientAsync
(
checClient
));
}
}
private
static
async
Task
HandleChecClientAsync
(
TcpClient
checClient
)
{
using
(
checClient
)
using
(
NetworkStream
checStream
=
checClient
.
GetStream
())
using
(
TcpClient
posbcClient
=
new
TcpClient
())
{
await
posbcClient
.
ConnectAsync
(
PosbcServer
,
PosbcPort
);
Console
.
WriteLine
(
"Conectado a POSBC."
);
using
(
NetworkStream
posbcStream
=
posbcClient
.
GetStream
())
{
Task
receiveFromPosbcTask
=
ReceiveFromPosbcAndSendToChecAsync
(
posbcStream
,
checStream
);
while
(
true
)
{
// Leer mensaje desde CHEC
byte
[]
lengthBuffer
=
new
byte
[
4
];
int
bytesRead
=
await
checStream
.
ReadAsync
(
lengthBuffer
,
0
,
4
);
if
(
bytesRead
==
0
)
break
;
// La conexión se ha cerrado
if
(
BitConverter
.
IsLittleEndian
)
{
Array
.
Reverse
(
lengthBuffer
);
}
int
messageLength
=
BitConverter
.
ToInt32
(
lengthBuffer
,
0
);
byte
[]
messageBuffer
=
new
byte
[
messageLength
];
bytesRead
=
await
checStream
.
ReadAsync
(
messageBuffer
,
0
,
messageLength
);
if
(
bytesRead
==
0
)
break
;
// La conexión se ha cerrado
// Remitir mensaje a POSBC
await
posbcStream
.
WriteAsync
(
lengthBuffer
,
0
,
4
);
await
posbcStream
.
WriteAsync
(
messageBuffer
,
0
,
messageLength
);
Console
.
WriteLine
(
$"Mensaje remitido a POSBC:
{
Encoding
.
UTF8
.
GetString
(
messageBuffer
)}
"
);
}
await
receiveFromPosbcTask
;
}
}
}
private
static
async
Task
ReceiveFromPosbcAndSendToChecAsync
(
NetworkStream
posbcStream
,
NetworkStream
checStream
)
{
byte
[]
buffer
=
new
byte
[
4096
];
while
(
true
)
{
// Leer longitud del mensaje desde POSBC
byte
[]
lengthBuffer
=
new
byte
[
4
];
int
bytesRead
=
await
posbcStream
.
ReadAsync
(
lengthBuffer
,
0
,
4
);
if
(
bytesRead
==
0
)
break
;
// La conexión se ha cerrado
if
(
BitConverter
.
IsLittleEndian
)
{
Array
.
Reverse
(
lengthBuffer
);
}
int
messageLength
=
BitConverter
.
ToInt32
(
lengthBuffer
,
0
);
byte
[]
messageBuffer
=
new
byte
[
messageLength
];
bytesRead
=
await
posbcStream
.
ReadAsync
(
messageBuffer
,
0
,
messageLength
);
if
(
bytesRead
==
0
)
break
;
// La conexión se ha cerrado
// Remitir mensaje a CHEC
await
checStream
.
WriteAsync
(
lengthBuffer
,
0
,
4
);
await
checStream
.
WriteAsync
(
messageBuffer
,
0
,
messageLength
);
Console
.
WriteLine
(
$"Mensaje remitido a CHEC:
{
Encoding
.
UTF8
.
GetString
(
messageBuffer
)}
"
);
}
}
}
gatewayGK/Servidor/TcpGatewayB.cs
0 → 100644
View file @
41a876af
using
System
;
using
System.Net
;
using
System.Net.Sockets
;
using
System.Text
;
using
GatewaySCO
;
using
Serilog
;
namespace
Servidor.TcpGatewayB
;
public
class
TcpGatewayB
{
private
const
int
GatewayPort
=
6698
;
private
const
string
PosbcServer
=
"127.0.0.1"
;
private
const
int
PosbcPort
=
6697
;
public
async
Task
Start
()
{
Log
.
Logger
=
new
LoggerConfiguration
()
.
WriteTo
.
Console
()
.
CreateLogger
();
try
{
TcpListener
gatewayListener
=
new
TcpListener
(
IPAddress
.
Any
,
GatewayPort
);
gatewayListener
.
Start
();
Log
.
Information
(
$"Gateway escuchando en el puerto
{
GatewayPort
}
..."
);
while
(
true
)
{
TcpClient
checClient
=
await
gatewayListener
.
AcceptTcpClientAsync
();
Log
.
Information
(
"CHEC conectado."
);
_
=
Task
.
Run
(()
=>
HandleChecClientAsync
(
checClient
));
}
}
catch
(
Exception
ex
)
{
Log
.
Error
(
ex
,
"Error en el Gateway"
);
}
finally
{
Log
.
CloseAndFlush
();
}
}
private
async
Task
HandleChecClientAsync
(
TcpClient
checClient
)
{
using
(
checClient
)
using
(
NetworkStream
checStream
=
checClient
.
GetStream
())
using
(
TcpClient
posbcClient
=
new
TcpClient
())
{
try
{
await
posbcClient
.
ConnectAsync
(
PosbcServer
,
PosbcPort
);
Log
.
Information
(
"Conectado a POSBC."
);
using
(
NetworkStream
posbcStream
=
posbcClient
.
GetStream
())
{
Task
receiveFromPosbcTask
=
ReceiveFromPosbcAndSendToChecAsync
(
posbcStream
,
checStream
);
while
(
true
)
{
// Leer mensaje desde CHEC
byte
[]
lengthBuffer
=
new
byte
[
4
];
int
bytesRead
=
await
checStream
.
ReadAsync
(
lengthBuffer
,
0
,
4
);
if
(
bytesRead
==
0
)
continue
;
// Si no se lee nada, continuar esperando
if
(
BitConverter
.
IsLittleEndian
)
{
Array
.
Reverse
(
lengthBuffer
);
}
int
messageLength
=
BitConverter
.
ToInt32
(
lengthBuffer
,
0
);
byte
[]
messageBuffer
=
new
byte
[
messageLength
];
bytesRead
=
await
checStream
.
ReadAsync
(
messageBuffer
,
0
,
messageLength
);
if
(
bytesRead
==
0
)
continue
;
// Si no se lee nada, continuar esperando
// Remitir mensaje a POSBC
byte
[]
bytesMsj
=
Util
.
ConcatenaArreglosBytes
(
lengthBuffer
,
messageBuffer
);
// await posbcStream.WriteAsync(lengthBuffer, 0, 4);
// await posbcStream.WriteAsync(messageBuffer, 0, messageLength);
await
posbcStream
.
WriteAsync
(
bytesMsj
,
0
,
bytesMsj
.
Length
);
Log
.
Information
(
$"Mensaje remitido a POSBC:
{
Encoding
.
UTF8
.
GetString
(
messageBuffer
)}
"
);
}
await
receiveFromPosbcTask
;
}
}
catch
(
Exception
ex
)
{
Log
.
Error
(
ex
,
"Error manejando la conexión CHEC"
);
}
}
}
private
async
Task
ReceiveFromPosbcAndSendToChecAsync
(
NetworkStream
posbcStream
,
NetworkStream
checStream
)
{
byte
[]
buffer
=
new
byte
[
4096
];
while
(
true
)
{
try
{
// Leer longitud del mensaje desde POSBC
byte
[]
lengthBuffer
=
new
byte
[
4
];
int
bytesRead
=
await
posbcStream
.
ReadAsync
(
lengthBuffer
,
0
,
4
);
if
(
bytesRead
==
0
)
continue
;
// Si no se lee nada, continuar esperando
if
(
BitConverter
.
IsLittleEndian
)
{
Array
.
Reverse
(
lengthBuffer
);
}
int
messageLength
=
BitConverter
.
ToInt32
(
lengthBuffer
,
0
);
byte
[]
messageBuffer
=
new
byte
[
messageLength
];
bytesRead
=
await
posbcStream
.
ReadAsync
(
messageBuffer
,
0
,
messageLength
);
if
(
bytesRead
==
0
)
continue
;
// Si no se lee nada, continuar esperando
// Remitir mensaje a CHEC
byte
[]
bytesMsj
=
Util
.
ConcatenaArreglosBytes
(
lengthBuffer
,
messageBuffer
);
// await checStream.WriteAsync(lengthBuffer, 0, 4);
// await checStream.WriteAsync(messageBuffer, 0, messageLength);
await
checStream
.
WriteAsync
(
bytesMsj
,
0
,
bytesMsj
.
Length
);
Log
.
Information
(
$"Mensaje remitido a CHEC:
{
Encoding
.
UTF8
.
GetString
(
messageBuffer
)}
"
);
}
catch
(
Exception
ex
)
{
Log
.
Error
(
ex
,
"Error recibiendo desde POSBC o enviando a CHEC"
);
break
;
}
}
}
}
gatewayPruebaECO/ProgramECO.cs
View file @
41a876af
...
...
@@ -158,7 +158,7 @@ public class SocketClientECO
Console
.
WriteLine
(
"Cliente ECO #1 Conectado al servidor."
);
// Enviar 4 mensajes de texto en formato binario
for
(
int
i
=
1
;
i
<=
4
;
i
++)
for
(
int
i
=
1
;
i
<=
1
;
i
++)
{
string
message
=
$"Mensaje
{
i
}
desde el cliente CHEC"
;
...
...
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