TCP listener is crashing when sending messages multiple times (random), and throw this exception, there is any solution to fix it?
Here is the exception:
System.IO.IOException: Unable to read data from the transport connection: An
established connection was aborted by the software in your host machine. ---
> System.Net.Sockets.SocketException: An established connection was aborted
by the software in your host machine
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32
size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32
size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32
size)
This is my TCP Listener code (marked the error line which threw exception):
static string serverstatus = "0";
try
{
server.Start();
Byte[] bytes = new Byte[256];
String data = null;
while (true)
{
TcpClient client = server.AcceptTcpClient();
data = null;
NetworkStream stream = client.GetStream();
int i;
//THROW THE ERROR
while ((i = stream.Read(bytes, 0, bytes.Length)) > 0)
{
data = System.Text.Encoding.UTF8.GetString(bytes, 0, i);
if (data != "0" && data != serverstatus)
{
serverstatus = data;
Console.WriteLine("Current Status is: " + serverstatus);
}
data = serverstatus.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(serverstatus);
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Server Sending Back: {0}", serverstatus);
}
}
}
catch (Exception _ex)
{
Console.WriteLine(_ex.ToString());
Console.ReadKey();
}
The .NET API exposes a closed or failed connection through an exception, which you encounter here. You need to handle the exception (close the stream, clean up things, etc.) and continue with going on to handle the next client.
And by the way:
stream.Read(bytes, 0, bytes.Length)
will not exactly read bytes.Length
bytes, but anything between 1 and bytes.Length
bytes. If you need exactly that amount of bytes you need to call it in a loop.
If serverStatus
is not exactly of bytes.Length
bytes the protocol also misses some framing information, since the client might have no idea how long to try to actually read data before trying to decode it as a message.