I choose not the use the asynchronous calls since it requires a callback, I’m just curious if there’s a way to solve this by utilizing Unix-alike non-blocking socket method: Poll(), as Asyn is created specifically for the Windows environment. I’m researching if this could be done without asynchronous.
To be noted: NON-BLOCKING != ASYNCHRONOUS🙂
Therefore I have the following approach by turning off the blocking flag of socket & Poll() method:
try
{
IPEndPoint hostEp = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000);
Socket hostSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
hostSock.Blocking = false;
hostSock.Connect(hostEp);
}
catch (Win32Exception se)
{
if (ex.ErrorCode == 10035) // WSAEWOULDBLOCK is expected, means connect is in progress
while (true)
{
Console.WriteLine("Connecting in progress");
bool connected = hostSock.Poll(1000000, SelectMode.SelectWrite);
if (connected)
{
Console.WriteLine("Connected");
break;
}
}
}
But then SelectMode.SelectWrite doesn’t seems reinitiates an connection attempts for me. So, what’s the problem? And how could I solve this? Should I use Select() instead of Poll()?
Just use the asynchronous methods (
ConnectAsync()), they’re meant for this. Don’t use exceptions for program logic.You can synchronously
Connect()a TCP socket without blocking:But that is exactly what your code does, so that should just work.