我正在用C#做一个嵌入式项目,我已经编写了一个基于套接字的Web服务器。一切都运作良好,除了我不能为我的生活得到请求的身体。 Content-Length表示有12个字符,但socket.Recieve方法只获取标题。
while (true)
{
using (Socket clientSocket = listeningSocket.Accept())
{
IPEndPoint clientIP = clientSocket.RemoteEndPoint as IPEndPoint;
Debug.Print("Received request from " + clientIP.ToString());
var x = clientSocket.RemoteEndPoint;
int availableBytes = clientSocket.Available;
Debug.Print(DateTime.Now.ToString() + " " + availableBytes.ToString() + " request bytes available");
int bytesReceived = (availableBytes > maxRequestSize ? maxRequestSize : availableBytes);
if (bytesReceived > 0)
{
byte[] buffer = new byte[bytesReceived]; // Buffer probably should be larger than this.
int readByteCount = clientSocket.Receive(buffer, bytesReceived, SocketFlags.None);
using (Request r = new Request(clientSocket, Encoding.UTF8.GetChars(buffer)))
{
Debug.Print(DateTime.Now.ToString() + " " + r.URL);
if (requestReceived != null) requestReceived(r);
}
}
}
Thread.Sleep(10);
}
availableBytes
= 499
bytesReceived
= 499
readByteCount
= 487(短12个字符)
我在这里缺少什么?如果有任何不同,正文是多部分表单数据。
答案 0 :(得分:1)
int bytesReceived = (availableBytes > maxRequestSize ? maxRequestSize : availableBytes);
如果maxRequestSize
为487,那么您将获得您描述的结果。
还要记住Content-Length
不是字节 - 它是八位字节:What's the "Content-Length" field in HTTP header?(好的我是迂腐的 - 八位字节是8位;)
答案 1 :(得分:0)
我想知道Available
属性有多可靠。它看起来只对非阻塞套接字有用,然后只作为一个布尔标志表示某些东西可用。
为什么不在循环中读取流来解析消息呢?