diff --git a/src/Connections/Elasticsearch.Net.Connection.Thrift/Transport/TSocket.cs b/src/Connections/Elasticsearch.Net.Connection.Thrift/Transport/TSocket.cs index 8211b8ab98b..51b7a01ec71 100644 --- a/src/Connections/Elasticsearch.Net.Connection.Thrift/Transport/TSocket.cs +++ b/src/Connections/Elasticsearch.Net.Connection.Thrift/Transport/TSocket.cs @@ -23,6 +23,7 @@ using System; using System.Net.Sockets; +using System.Threading; namespace Elasticsearch.Net.Connection.Thrift.Transport { @@ -33,6 +34,55 @@ public class TSocket : TStreamTransport private TcpClient client; private int timeout; + private bool isConnectionSuccessful = false; + private Exception socketexception; + private ManualResetEvent timeoutObject = new ManualResetEvent(false); + + public TcpClient Connect() + { + timeoutObject.Reset(); + socketexception = null; + + client.BeginConnect(host, port, new AsyncCallback(CallBackMethod), client); + + if (timeoutObject.WaitOne(timeout, false)) + { + if (isConnectionSuccessful) + { + return client; + } + + throw socketexception ?? new Exception("Socket exception should not be null."); + } + + client.Close(); + throw new TimeoutException("TimeOut Exception"); + } + + private void CallBackMethod(IAsyncResult asyncresult) + { + try + { + isConnectionSuccessful = false; + var tcpclient = asyncresult.AsyncState as TcpClient; + + if (tcpclient != null && tcpclient.Client != null) + { + tcpclient.EndConnect(asyncresult); + isConnectionSuccessful = true; + } + } + catch (Exception ex) + { + isConnectionSuccessful = false; + socketexception = ex; + } + finally + { + timeoutObject.Set(); + } + } + public TSocket(TcpClient client) { this.client = client; @@ -121,14 +171,7 @@ public override void Open() InitSocket(); } - - var connectionRequest = client.BeginConnect(host, port, null, null); - var connected = connectionRequest.AsyncWaitHandle.WaitOne(this.ConnectTimeout); - - if (!connected) - { - throw new TTransportException("Failed to connect"); - } + client = Connect(); inputStream = client.GetStream(); outputStream = client.GetStream();