Question

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)
        {
Était-ce utile?

La 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.

Autres conseils

From my experience this exception is only thrown when what ever you are connecting to closes the connection. If this is across the internet there are many hops along the way that may be responsible for dropping the connection. If you are convinced that this shouldn't be happening (maybe both sides are in your infrastructure) then I would recommend running a wireshark trace. There you will easily be able to see a connection being closed if it is being closed and who is it closing. Look for tcp packets with the fin flag set to 1.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top