C#TCP侦听器崩溃

时间:2017-12-29 20:00:14

标签: c# tcp tcpclient tcplistener

TCP侦听器在多次(随机)发送消息时崩溃,并抛出此异常,有任何解决方案可以修复它吗?

以下是例外:

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)

这是我的TCP侦听器代码(标记了引发异常的错误行):

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();
}

1 个答案:

答案 0 :(得分:1)

.NET API通过您在此处遇到的异常公开已关闭或失败的连接。您需要处理异常(关闭流,清理事物等)并继续处理下一个客户端。

顺便说一下:

stream.Read(bytes, 0, bytes.Length)不会完全读取bytes.Length个字节,而是1到bytes.Length个字节之间的任何内容。如果您需要确切的字节数,则需要在循环中调用它。

如果serverStatus不完全是bytes.Length个字节,协议也会错过某些成帧信息,因为客户端可能不知道在尝试将数据解码为消息之前尝试实际读取数据需要多长时间