_NetworkClient = Connect(remoteEndPoint, 4000);
private static ManualResetEvent waitob = new ManualResetEvent(false);
private static Exception asynexception;
public static TcpClient Connect(IPEndPoint remoteEndPoint, int timeoutMSec)
{
string host = Convert.ToString(remoteEndPoint.Address);
int portNo = remoteEndPoint.Port;
waitob.Reset();
asynexception = null;
TcpClient tc = new TcpClient();
IAsyncResult iar = tc.BeginConnect(host, portNo, new AsyncCallback(ConnectCallBack), tc);
if (waitob.WaitOne(timeoutMSec, false))
{
if (asynexception == null)
{
return tc;
}
else
{
throw asynexception;
}
}
else
{
tc.Close();
throw new TimeoutException("Timeout");
}
}
private static void ConnectCallBack(IAsyncResult ar)
{
try
{
TcpClient client = ar.AsyncState as TcpClient;
if (client.Client != null)
{
client.EndConnect(ar);
}
else
{
}
}
catch (Exception ex)
{
asynexception = ex;
}
finally
{
waitob.Set();
}
}
Subscribe to:
Post Comments (Atom)
1 comment:
THANKS SO MUCH!!
worked like a charm!!
Post a Comment