你當然可以創建自己的HttpHeader
來處理,但你最終還是不得不建立在HTTP它傳遞給send()
之前手動頭,例如:
struct HttpHeader
{
char *Version;
char *Status;
char *ContentType;
};
char* HttpHeaderToString(HttpHeader *hdr)
{
int len = strlen(hdr->Version) + strlen(hdr->Status) + 10;
if (strlen(hdr->ContentType) > 0)
len += (strlen(hdr->ContentType) + 16);
//...
char *str = (char*) malloc(len);
if (str != NULL)
{
sprintf(str, "HTTP/%s %s\r\n", hdr->Version, hdr->Status);
if (strlen(hdr->ContentType) > 0)
{
strcat(str, "Content-Type: ");
strcat(str, hdr->ContentType);
strcat(str, "\r\n");
}
//...
strcat(str, "\r\n");
}
return str;
}
HttpHeader h;
h.Version = "1.0";
h.Status = "200 OK";
h.ContentType = HTTP_CONTENT_TYPE_TEXT_XML;
...
char *str = HttpHeaderToString(&h);
if (str != NULL)
{
send(ClientSocket, str, strlen(str), 0);
free(str);
}
另一方面,TCP是一個字節流,因此您不必在單個呼叫中發送所有內容。您可以撥打send()
多次,因爲你需要,如(檢查省略誤差爲簡潔起見):
void SendHttpHeader(HttpHeader *hdr)
{
send(ClientSocket, "HTTP/", 5, 0);
send(ClientSocket, hdr->Version, strlen(hdr->Version), 0);
send(ClientSocket, " ", 1, 0);
send(ClientSocket, hdr->Status, strlen(hdr->Status), 0);
send(ClientSocket, "\r\n", 2, 0);
if (strlen(hdr->ContentType) > 0)
{
send(ClientSocket, "Content-Type: ", 14, 0);
send(ClientSocket, hdr->ContentType, strlen(hdr->ContentType), 0);
send(ClientSocket, "\r\n", 2, 0);
}
//...
send(ClientSocket, "\r\n", 2, 0);
}
HttpHeader h;
h.Version = "1.0";
h.Status = "200 OK";
h.ContentType = HTTP_CONTENT_TYPE_TEXT_XML;
...
SendHttpHeader(&h);
這是可用於C++ http://httplib.codeplex.com/如果有任何幫助 –
或[WinHTTP](http://msdn.microsoft.com/en-us/library/windows/desktop/aa382925(v = vs.85).aspx)如果你想堅持本機窗口 – Mgetz