10

I am building a Mock Server using TCPListener.

When I tried to debug my code by running the client, I was able to read the request on the server. But on the client side, an exception is being thrown. Here is the exception I got from the trace:

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

Here is the code of I implemented on the server:

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

Edit

I also tried to disable my firewall but the exception still occurs.

Ray
  • 597
  • 1
  • 6
  • 17
  • You are closing the connection before the client has had a chance of reading the data. NEVER close a connection on the server. The client should always open the connection and close the connection. To close the application on server, capture the close event which will occur when the client closes the connection. – jdweng Aug 11 '15 at 04:01

1 Answers1

3

Setting the correct Content-Length fixed it.

If Content-Length is greater than the actual length, the client-side will continue to wait for the remaining parts of the response. But since the server is already done with sending the response, it will end the process.

Ray
  • 597
  • 1
  • 6
  • 17