From 07bf03780640745720a950e57498fa4dc4a65d83 Mon Sep 17 00:00:00 2001 From: Garr Godfrey Date: Wed, 28 Jul 2021 18:20:10 -0700 Subject: [PATCH] handle connection timeout --- .../PAX/Interfaces/PaxTcpInterface.cs | 28 ++++++++++++++++--- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/src/GlobalPayments.Api/Terminals/PAX/Interfaces/PaxTcpInterface.cs b/src/GlobalPayments.Api/Terminals/PAX/Interfaces/PaxTcpInterface.cs index e152efcf..dc263d0c 100644 --- a/src/GlobalPayments.Api/Terminals/PAX/Interfaces/PaxTcpInterface.cs +++ b/src/GlobalPayments.Api/Terminals/PAX/Interfaces/PaxTcpInterface.cs @@ -21,10 +21,20 @@ public PaxTcpInterface(ITerminalConfiguration settings) { public void Connect() { if (_client == null) { - _client = new TcpClient(); - _client.ConnectAsync(_settings.IpAddress, int.Parse(_settings.Port)).Wait(_settings.Timeout); - _stream = _client.GetStream(); - _stream.ReadTimeout = _settings.Timeout; + try + { + _client = new TcpClient(); + _client.ConnectAsync(_settings.IpAddress, int.Parse(_settings.Port)).Wait(_settings.Timeout); + _stream = _client.GetStream(); + _stream.ReadTimeout = _settings.Timeout; + } + catch (Exception) + { + // don't leave _client set without a _stream + _client?.Dispose(); + _client = null; + throw; + } } _connectionCount++; } @@ -44,7 +54,17 @@ public byte[] Send(IDeviceMessage message) { byte[] buffer = message.GetSendBuffer(); Connect(); + try { + if (_stream == null) + { + // can be null if another thread is opening and waiting for connection. + // typical when Cancel is called. We've increased the connection + // count but cannot actually use it. + throw new MessageException("Terminal is not yet ready."); + } + + for (int i = 0; i < 3; i++) { _stream.WriteAsync(buffer, 0, buffer.Length).Wait();