0

My method that starts my Asynchronous Client Socket blocks when it calls .BeginConnect() while waiting for connection.

I want the method to be async and want to 'await' connection instead of blocking, so that caller can continue while waiting for connection.

        public static async Task start_connection() 
    {  
        // Connect to a remote device.  
        try {  
            IPAddress ipAddress =  IPAddress.Parse( App.SYSTEM_HUB_IP );
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);  

            // Create a TCP/IP socket.  
            Socket client_Socket = new Socket(ipAddress.AddressFamily,  
                SocketType.Stream, ProtocolType.Tcp);  


                // .BeginConnect blocks.   

<<<<<<<< 'await' ON NEXT LINE CAUSES COMPILER ERROR

            client_Socket.BeginConnect( remoteEP,   new AsyncCallback(ConnectCallback), client_Socket);                 connectDone.WaitOne();  

        } catch (Exception e) {  
            Console.WriteLine(e.ToString());  
        }  
    }  

I do not see any solution for async client connection in "This question already has an answer here". All I see there is async listener (ie. server, not client). My socket service is already async. But I can find no example of async client initiating connection.

Specifically, how do I use async/wait to prevent .BeginConnect from blocking?

Doug Null
  • 7,989
  • 15
  • 69
  • 148
  • 1
    What about ConnectAsync()? Have a look at [this](https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.connectasync?view=netframework-4.7.2) – croxy Dec 19 '18 at 17:03
  • 1
    @croxy That has the same fundamental problem. – Servy Dec 19 '18 at 17:05
  • I do not see any solution for async client connection in "This question already has an answer here". All I see there is async listener (ie. server, not client). My socket service is already async. But I can find no example of async client initiating connection. – Doug Null Dec 21 '18 at 23:56

0 Answers0