2

This code works ok if the list of connections is small, but if I try to connect to 20 different IPs, many of them being wrong IPs, the BeginConnect takes too much time. For example, if I have a list of IPs, with the first 19 being wrong IPs (the connection should fail for these, because there is no machine with that IP or because my server is not running in the machine with that IP) and the last one is the correct one, it takes a lot of seconds, more than 50 seconds, to connect. Instead, if the first BeginConnect is done with the correct IP, the connection is established very fast.

foreach(string ip in ips)
{
     client = new TcpClient();
     client.BeginConnect(System.Net.IPAddress.Parse(ip), port, new AsyncCallback(ConnectCallback), client);
}

In the connect callback, if the connection is established I launch the BeginRead

private void ConnectCallback(IAsyncResult result)
{
        TcpClient client = (TcpClient)result.AsyncState;
        try
        {
            if (client != null && client.Client != null)
                client.EndConnect(result);                    
            else
                return;
        }
        catch
        {
            if (client != null && client.Client != null)
                client.Close();
            return;
        }

        if (client != null && client.Client != null)
        {
            NetworkStream networkStream = client.GetStream();
            byte[] buffer = new byte[client.ReceiveBufferSize];
            networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);
        }
    }

with the waitOne option the connection is not established

            IAsyncResult asyncResult = client.BeginConnect(System.Net.IPAddress.Parse(ip), port, null, null);
            if ( asyncResult.AsyncWaitHandle.WaitOne(1000, false) )
            {                 
                client.EndConnect(asyncResult);
                NetworkStream networkStream = client.GetStream();
                byte[] buffer = new byte[client.ReceiveBufferSize];
                networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);
            }

The problem is caused by the IPs that are not assigned to any machine. If I call BeginConnect with any of those IPs, all the connections are blocked and none of the valid connections is established. I solved the problem sending a ping before trying the connection. If the ping does not respond I don't begin the connection with that IP.

            Ping ping = new Ping();
            PingReply reply = ping.Send(System.Net.IPAddress.Parse(ip));
            if (reply.Status == IPStatus.Success)
            {
               client = new TcpClient();
               client.BeginConnect(System.Net.IPAddress.Parse(ip), m_port, new AsyncCallback(ConnectCallback), client);
            }

0 Answers0