C#TCP侦听器崩溃

问题描述 投票:-1回答:1

多次发送消息(随机)时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();
}
c# tcp tcpclient tcplistener
1个回答
1
投票

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

顺便说一下:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.