1
POST 요청을 사용하기위한 작은 Windows 응용 프로그램을 구축 중입니다. 아래의 코드는 GET 요청 및 첫 번째 POST 요청에 대해 잘 작동합니다. 기본적으로 POST DATA를 읽으면 처음에는 (또는 처음 몇 번) 제대로 작동합니다. ..?. 그것은 들어오는 요청이 중단 어떤 아이디어 중단 컨텐츠 길이가 일치 가정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, 당신은 할 수있다 Yannis 제안으로
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();
}
는'ReadLin 무엇입니까 e'? 디버거를 일시 중지하면 어디서 멈 춥니 까? bst와 client에'using' 블록을 사용하십시오. – usr
사용하는 블록에 대해 걱정하지 마십시오. 그것들은 관련이 없습니다. 백만 가지가이 코드에 대해 더 나을 수 있지만 왜 블록하는지에 관심이 있습니다. – Yannis
그것은 ReadLine에서 블록합니다 – Yannis