Search code examples
c#asp.nettcpclient

TcpClient.BeginConnect(host, port, null, null); gives random success


In my code, I'm trying to connect to a relay board using a timer which invokes a method with every tick. The problem is that when I run my application, I get a connection successfully for the first 3-4 ticks. But, after that it fails to connect. I'm unable to figure out what is wrong in my code. Any help would be appreciated. I'm working with asp.net

The method invoked:

private void open_ethernet_connection()
{
    byte connected = 0;

    TcpClient client = new TcpClient();
    try
    {

        IAsyncResult result = client.BeginConnect(textBox_IP.Text.Substring(0, textBox_IP.Text.IndexOf(",")), GlobalClass.port, null, null);
        bool success = result.AsyncWaitHandle.WaitOne(1000, true);

        if (!success)
        {
            connected = 0;
            client.Close();
            Response.Write("Failed to connect");
        }
        else connected = 1;

        if (connected == 1)
        {
            ns = client.GetStream();
            ns.ReadTimeout = 1000;
            SerBuf[0] = (byte)commands.GET_VER;     // get version command for ETH RLY16/02, returns software version
            transmit(1);
            receive(3);
            module_version = SerBuf[2];  //print the software version on screen
            device_found = true;
        }
    }
    catch (SocketException)
    {
        if (selected_port == "Custom IP")
        {
            Response.Write("Unable to connect to module at " + GlobalClass.ipaddress);
        }
        else Response.Write("Unable to connect to module at " + selected_port);
        return;
    } 
}

Solution

  • you never close your connection if its successful.

    consider using using https://msdn.microsoft.com/sv-SE/library/yh598w02.aspx

    using (TcpClient client = new TcpClient())
    {
       Other code here...
    }
    

    This way your TcpClient is always disposed and you don't have to call .Close()