我正在建立一个小窗口应用程序消耗POST请求。下面的代码适用于GET请求和第一个POST请求。基本上,当我读取POST数据时,它第一次(或前几次)工作正常。 。?它挂任何传入请求挂起任何想法假设内容长度是正确的一个简单的Web服务器消耗POST请求 - 服务器挂起后,一个或两个请求
while (true)
{
System.Console.WriteLine("The server is running at port 8001...");
System.Console.WriteLine("Waiting for a connection.....");
TcpClient client = _listener.AcceptTcpClient();
int incomingDataLength = client.ReceiveBufferSize;
Stream ist = client.GetStream();
BufferedStream bst = new BufferedStream(ist);
int k = 0;
String line = ReadLine(bst);
System.Console.WriteLine(line);
while ((line = ReadLine(bst)) != null)
{
if (line == "") break;
System.Console.WriteLine(line);
}
MemoryStream ms = new MemoryStream();
int contentLen = 3429;
//if (this.HttpHeaders.ContainsKey("Content-Length"))
{
//content_len = Convert.ToInt32(this.HttpHeaders["Content-Length"]);
byte[] buf = new byte[4096];
int to_read = content_len;
while (to_read > 0)
{
int numread = bst.Read(buf, 0, Math.Min(buf.Length, to_read));
if (numread == 0)
{
if (to_read == 0) break;
else throw new Exception("client disconnected during post");
}
to_read -= numread;
ms.Write(buf, 0, numread);
}
ms.Seek(0, SeekOrigin.Begin);
}
using (StreamReader sr = new StreamReader(ms))
{
System.Console.WriteLine(sr.ReadToEnd());
}
bst.Close();
client.Close();
而且Readline正
private String ReadLine(Stream stream)
{
int k;
StringBuilder lineBuilder = new StringBuilder();
while (true)
{
k = stream.ReadByte();
if (k < 0) continue;
char c = Convert.ToChar(k);
if (c == '\n') break;
if (c == '\r') continue;
lineBuilder.Append(c);
}
return lineBuilder.ToString();
}
2014-01-11
Yannis
+0
什么是'ReadLin e'?暂停调试器时,它会在哪里挂起?为bst和客户端使用'使用'块。 –
+0
不要担心使用块。它们不相关。有一百万件事情可以对此代码更好,但我对它为什么会阻塞感兴趣。 –
+0
它在ReadLine中阻止 –