Search code examples
c#connectiontcpclientnetstream

NetStream TcpClinet Unable to read data from the transport connection


I am using TcpClient. Sometimes get an error:

Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)

I tried to resolve by information from stackoverflow contributions. I add condition

netStream.CanRead

but without success. What I am doing wrong? Here se part of code, thanks.

try
        {
            if (netStream.CanRead)
            {
                do
                {
                    int bytesRead = netStream.Read(bytes, 0, bytes.Length);
                    bytesReaded += bytesRead;
                    if (bytesRead > 0)
                    {
                        byte[] toList = new byte[bytesRead];
                        Array.Copy(bytes, toList, bytesRead);
                        listBytes.AddRange(toList);
                    }
                }
                while (netStream.DataAvailable);

                if (listBytes.Count > 0)
                    ParseAllBytes();
            }
            else
            {                    
                Close();
            }
        }
        catch (IOException ex)
        {

Solution

  • Problem is in windows firewall, If I turn off firewall working perfectly. If firewall is turn on and I added rule to inbouds and outbounds, I gets this exception, see on top.