-1

I made a server-client program with auto connection. But the program only works if I first start the server application because the client needs to connect. My goal is for the client to check with a delay of 2 seconds if the server is already created. I made a while statement for a trial and error cycle

try
{
    int a = 1;
    while (a == 1)
    {
        cliente.Connect(IP_End);
        if (cliente.Connected)
        {
            connectRead();
            a = 2;
        }
        else
        {
            while (!cliente.Connected)
            {
                int milliseconds = 2000;
                Thread.Sleep(milliseconds);
                cliente.Connect(IP_End);
                MessageBox.Show(text);

                if (cliente.Connected)
                {
                    connectRead();
                }
            }
        }
    }
}
catch(SocketException se)
{
    MessageBox.Show(se.Message);
}
catch(Exception ex)
{
    MessageBox.Show(ex.Message);
}

the error is :

No connection can be made because the target computer actively refused them 192.168.254.28:100

the method is here :

private void connectRead()
{
    STW = new StreamWriter(cliente.GetStream());
    STR = new StreamReader(cliente.GetStream());
    STW.AutoFlush = true;

    backgroundWorker1.RunWorkerAsync();
    backgroundWorker1.WorkerSupportsCancellation = true;
}
interesting-name-here
  • 1,851
  • 1
  • 20
  • 33

2 Answers2

0

Without knowing more about errors or desired functionality, I can tell you will call connectRead(); twice if you hit the second loop. To fix this replace your second loop with this:

while (!cliente.Connected)
{
    int milliseconds = 2000;
    Thread.Sleep(milliseconds);
    cliente.Connect(IP_End);

    if (cliente.Connected)
    {
        connectRead();
        a = 2;
    }
}

EDIT: I also took out the MessageBox because that seems unnecessary and will pause the program until you hit Ok on the MessageBox.

EDIT 2:

Question on actively refused connections

Question on determination of open port

Community
  • 1
  • 1
interesting-name-here
  • 1,851
  • 1
  • 20
  • 33
0

Based on the code you almost got it right. I believe the "Connect" extension method should update the value within the client. If it does the way I'd do it would be to introduce a separate method that returns a boolean and it would help to simplify the code. For example:

private bool ConnectClient(SomeClient clientToConnect, IPAddress ipToConnectTo, int delay)
{
    System.Threading.Thread.Sleep(delay);
    clientToConnect.Connect(ipToConnectTo);
    return clientToConnect.Connected;
}

try
{
    bool successfulConnection;

    while (!successfulConnection)
    {
        successfulConnection = ConnectClient(yourClient, "10.10.10.10", 2000);
    }
}
catch
{
// ...
}
Philip P.
  • 1,162
  • 1
  • 6
  • 15