You already asked a similar question here. Using BeginConnect
is not a recommended approach at all. Using ConnectAsync
with an auto-cancelling source as discussed in the other thread solves the problem you are having here.
A community member has associated this post with a similar question:
C# TcpClient/TcpListener / Full Duplex Communication / Sample
Only moderators can edit this content.
C# AsyncWaitHandle.WaitOne - Socket
Markus Freitag
3,786
Reputation points
Hello,
Why doesn't the connection attempt wait 15 seconds?
How can I achieve that the client gets up to 15 seconds for a connection?
Socket or TcpClient. Thanks for your help!
//Create IP address and port number;
System.Net.IPAddress ip = IPAddress.Parse(Ipbox.Text);
int port = Convert.ToInt32(PortBox.Text);
IPEndPoint iPEndPoint = new IPEndPoint(ip, port);
//Determine whether you can connect to the server
try
{
//socket.Connect(iPEndPoint);
var result = socket.BeginConnect(iPEndPoint, null, null);
bool success = result.AsyncWaitHandle.WaitOne(15000, true);
if (success)
{
socket.EndConnect(result);
}
else
{
socket.Close();
throw new SocketException(10060); // Connection timed out.
}
{count} votes
1 answer
Sort by: Most helpful
-
Michael Taylor 48,281 Reputation points
2023-02-09T23:02:00.3333333+00:00