C# - 已建立的连接被主机错误中的软件中止

C# - an established connection was aborted by the software in your host machine Error

我正在使用 TCPListener 构建模拟服务器。

当我尝试通过 运行 客户端调试我的代码时,我能够读取服务器上的请求。但是在客户端,抛出异常。这是我从跟踪中得到的异常:

System.ServiceModel.CommunicationException: The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:05:00'. ---> 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

这是我在服务器上实现的代码:

TcpClient client = listener.AcceptTcpClient();
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
var dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);

byte[] sendBytes = null;
try
{
    var output = "POST HTTP/1.1 200 OK\r\n";
    output += "Server: Apache-Coyote/1.1\r\n";
    output += "Content-Type: application/soap+xml\r\n";
    output += "Content-Length: 632\r\n";
    output += "Date: Thu, 06 Aug 2015 02:06:39 GMT\r\n\r\n";
    output +=
        "<S:Envelope xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\"><S:Header></S:Header><S:Body></S:Body></S:Envelope>";
    sendBytes = Encoding.ASCII.GetBytes(output);
    nwStream.Write(sendBytes, 0, sendBytes.Length);
    nwStream.Flush();
}
catch (SocketException se)
{
    throw;
}

client.Close();

编辑

我也试过关闭我的防火墙,但还是出现异常。

设置正确的 Content-Length 修复了它。

如果Content-Length大于实际长度,客户端将继续等待响应的剩余部分。但由于服务器已经完成发送响应,它将结束该过程。