0

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)
        {
Musketyr
  • 745
  • 1
  • 16
  • 37

2 Answers2

1

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.

Musketyr
  • 745
  • 1
  • 16
  • 37
0

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.

uriDium
  • 13,110
  • 20
  • 78
  • 138
  • It will be hard to used wireshark, therefore this error is not periodical. With this problem, after disconnect, the client cannot connect againt to TcpClient. I have to restart service. Is this problem has relationship with error? – Musketyr May 27 '13 at 10:42
  • You might need to recreate your socket or TcpClient unless you have the reuse socket set properly. I have never got it to work. I always create a brand new socket. I am not sure if TcpClient has the same resuse idea as the socket does. – uriDium May 27 '13 at 11:12
  • Processing incomming data is for every client in new Thread in new instance of TcpClient. After error is TcpClient and NetStream Disposed properly. – Musketyr May 28 '13 at 06:21