我的代码有问题。当我在C#服务器中向C ++客户端发送响应时,我最终得到了奇怪的响应。
注意:DownloadData
方法仅从服务器接收数据,而没有其他内容。
C#响应句柄:
void HandleHttpRequest(object client)
{
HttpListenerContext cc = (HttpListenerContext)client;
cc.Response.Headers.Add("Test: Foo");
cc.Response.OutputStream.Write(Encoding.Default.GetBytes("Foo"), 0, Encoding.Default.GetBytes("Foo").Length);
cc.Response.Close();
}
C ++客户端
void DoHttpRead()
{
char* downloadedHttpBodyAndHeaders = DownloadData("127.0.0.1:49578");
cout << string(downloadedHttpBodyAndHeaders) << endl;
}
DownloadData函数
char* DownloadData(string url)
{
WSADATA wsaData;
int iResult;
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
return "error";
}
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
iResult = getaddrinfo("127.0.0.1", "49578", &hints, &result);
if (iResult != 0) {
WSACleanup();
return "error";
}
SOCKET ConnectSocket = INVALID_SOCKET;
ptr = result;
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
freeaddrinfo(result);
WSACleanup();
return "error";
}
iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
WSACleanup();
return "error";
}
int recvbuflen = 10000000;
char* recvbuf = new char[recvbuflen];
char sendbuffer[] = "GET / HTTP/1.1\r\nContent-Type: application/x-www-form-urlencoded\r\nHost: 127.0.0.1\r\nContent-Length: 1\r\n\r\n ";
iResult = send(ConnectSocket, sendbuffer, sizeof(sendbuffer), 0);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
WSACleanup();
return response;
}
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
WSACleanup();
return "error";
}
char* received = new char[512];
int totalBytesRead = 0;
{
do {
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if (iResult > 0) {
if (iResult <= 0)
break;
received = (char*)realloc(recvbuf, iResult + totalBytesRead);
memcpy(received + totalBytesRead, recvbuf, iResult);
totalBytesRead += iResult;
}
else {
break;
}
} while (iResult > 0);
}
closesocket(ConnectSocket);
WSACleanup();
char* received2 = new char[totalBytesRead];
memcpy(received2, received, totalBytesRead);
delete[] received;
return received2;
}
C ++客户端Http主体被弄乱了。不仅是“ Foo”,它还显示为
//headers
e
Foo
8
如何在http正文中仅获取Foo文本?