Skip to content

Commit 0c2ae72

Browse files
committed
Calling EndConnect after succeded async connection
1 parent a9211a5 commit 0c2ae72

File tree

1 file changed

+51
-8
lines changed
  • src/Connections/Elasticsearch.Net.Connection.Thrift/Transport

1 file changed

+51
-8
lines changed

src/Connections/Elasticsearch.Net.Connection.Thrift/Transport/TSocket.cs

Lines changed: 51 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323

2424
using System;
2525
using System.Net.Sockets;
26+
using System.Threading;
2627

2728
namespace Elasticsearch.Net.Connection.Thrift.Transport
2829
{
@@ -33,6 +34,55 @@ public class TSocket : TStreamTransport
3334
private TcpClient client;
3435
private int timeout;
3536

37+
private bool isConnectionSuccessful = false;
38+
private Exception socketexception;
39+
private ManualResetEvent timeoutObject = new ManualResetEvent(false);
40+
41+
public TcpClient Connect(TcpClient _client)
42+
{
43+
timeoutObject.Reset();
44+
socketexception = null;
45+
46+
client.BeginConnect(host, port, new AsyncCallback(CallBackMethod), client);
47+
48+
if (timeoutObject.WaitOne(timeout, false))
49+
{
50+
if (isConnectionSuccessful)
51+
{
52+
return client;
53+
}
54+
55+
throw socketexception ?? new Exception("Socket exception should not be null.");
56+
}
57+
58+
client.Close();
59+
throw new TimeoutException("TimeOut Exception");
60+
}
61+
62+
private void CallBackMethod(IAsyncResult asyncresult)
63+
{
64+
try
65+
{
66+
isConnectionSuccessful = false;
67+
var tcpclient = asyncresult.AsyncState as TcpClient;
68+
69+
if (tcpclient != null && tcpclient.Client != null)
70+
{
71+
tcpclient.EndConnect(asyncresult);
72+
isConnectionSuccessful = true;
73+
}
74+
}
75+
catch (Exception ex)
76+
{
77+
isConnectionSuccessful = false;
78+
socketexception = ex;
79+
}
80+
finally
81+
{
82+
timeoutObject.Set();
83+
}
84+
}
85+
3686
public TSocket(TcpClient client)
3787
{
3888
this.client = client;
@@ -121,14 +171,7 @@ public override void Open()
121171
InitSocket();
122172
}
123173

124-
125-
var connectionRequest = client.BeginConnect(host, port, null, null);
126-
var connected = connectionRequest.AsyncWaitHandle.WaitOne(this.ConnectTimeout);
127-
128-
if (!connected)
129-
{
130-
throw new TTransportException("Failed to connect");
131-
}
174+
client = Connect(client);
132175

133176
inputStream = client.GetStream();
134177
outputStream = client.GetStream();

0 commit comments

Comments
 (0)