notInThisForTheMoney
notInThisForTheMoney

Reputation: 41

C# Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. Reading networkstream

I have looked at

I am new to this and I have been told the issue is not the server. Is there anyway the issue can be client side or the client is causing an issue that forces the server to disconnect?

I make my connection

_client.BeginConnect(host, port, ConnectCallback, null);

and then in ConnectCallback

_client.EndConnect(result);`
_client.NoDelay = true;`
_client.ReceiveBufferSize = 65535;`
NetworkStream ns = _client.GetStream();`
byte[] buffer = new byte[_client.ReceiveBufferSize];`
ns.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);`

and then in ReadCallback

ns = _client.GetStream();`
read = ns.EndRead(result);`

Which is where it sometimes fails. There are other connections in the app and they have no problems. One of the connections is to the same server that I am having issues, but on a different port.

All the machines are on the same network. This is the only client connecting to this particular server/port. We run the app for about 3 hours and this error happens anytime.

Edit I appreciate the comments and input. Being new to programming and networking, etc, I still have the question: Is it possible the client is causing the issue?

Upvotes: 2

Views: 22231

Answers (1)

Rowan Smith
Rowan Smith

Reputation: 2180

The remote endpoint or a device on the network is closing the TCP connection.

You always need to test that the TCP connection is available and connected before reading from it.

You have no control over when the remote endpoint closes the connection. Even if you wrote the code on the remote endpoint it could still close due to a power outage.

The ReadCallback will be fired when the connection is closed, as well as when data is available. Your code is responsible for detecting that the connection has been closed and taking the necessary action in your code to deal with this scenario.

The easiest way to deal with this is to catch the exception, stop reading/writing from/to the socket, do any clean up tasks and reconnect if necessary etc etc..

Upvotes: 1

Related Questions