Yes, thank you for answering after all.
First look looks good.
Unfortunately it does not work either. Timeout comes much too fast.
Test it with 125000ms. Then you see immediately that it does not work. Too bad, maybe you have a tip.
I don't know how the experts solve it. The problem is actually simple. Give the client 15, 30 or 60 seconds to connect.
public void Connect(IPEndPoint remoteEndPoint, int timeoutMSec)
{
TimeoutObject.Reset();
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.BeginConnect(remoteEndPoint, CallBackMethod, socket);
//block the current thread
if (TimeoutObject.WaitOne(timeoutMSec, false))
//if (!TimeoutObject.WaitOne(timeoutMSec, false)) // ######
{
Log("Port is ok");
Thread th = new Thread(receive);
th.IsBackground = true;
th.Start();
}
else
{
Log("timeout");
}
}
//--asynchronous callback method
private void CallBackMethod(IAsyncResult asyncresult)
{
//Make a blocked thread continue
TimeoutObject.Set();
}
private void ConncectB_Click(object sender, EventArgs e)
{
try
{
//Create IP address and port number;
IPAddress ip = IPAddress.Parse(Ipbox.Text);
int port = Convert.ToInt32(PortBox.Text);
IPEndPoint iPEndPoint = new IPEndPoint(ip, port);
Connect(iPEndPoint, 125000); // #####
}
catch
{
socket = null;
Log("Input error");
}
Second and third try. Nothing works as expected
TimeoutObject.Reset();
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var result = socket.BeginConnect(remoteEndPoint, CallBackMethod, socket);
WaitHandle wait = result.AsyncWaitHandle;
//block the current thread
//if (TimeoutObject.WaitOne(timeoutMSec, false))
if (wait.WaitOne(timeoutMSec))
//if (!TimeoutObject.WaitOne(timeoutMSec, false))
{
Log("Port is ok");
Thread th = new Thread(receive);
th.IsBackground = true;
th.Start();
}
else
{
Log("timeout");
}