我正在使用TCPListener构建一个Mock服务器 .
当我尝试通过运行客户端来调试我的代码时,我能够在服务器上读取请求 . 但在客户端,正在抛出异常 . 以下是我从跟踪中获得的异常:
System.ServiceModel.CommunicationException:套接字连接已中止 . 这可能是由于处理消息的错误或远程主机超出接收超时或基础网络资源问题引起的 . 本地套接字超时为'00:05:00' . ---> System.IO.IOException:无法从传输连接读取数据:已 Build 的连接已被主机中的软件中止 . ---> System.Net.Sockets.SocketException:已 Build 的连接已被主机中的软件中止
这是我在服务器上实现的代码:
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
我也尝试禁用我的防火墙,但仍然会发生异常 .
1 回答
设置正确的Content-Length会修复它 .
如果Content-Length大于实际长度,则客户端将继续等待响应的其余部分 . 但由于服务器已完成发送响应,因此它将结束该过程 .