我在从远程服务器接收数据时遇到问题。似乎我可以向http://www.google.com之类的主机发送 HTTP 请求,但我无法得到回复。我正在向主机发送格式如下的 HTTP 1.0 请求:
GET / HTTP/1.0
主机:www.google.com
连接:关闭
这是代理代码的一部分:
//Parse Request Buffer
HttpRequest req;
req.ParseRequest(request.c_str(), request.length());
//Format Data to be Sent:
req.AddHeader ("Connection", "close"); // add connection close headers
req.SetVersion ("1.0"); // set http 1.0 flag
char *requestBuf = new char [req.GetTotalLength()];
req.FormatRequest(requestBuf);
//Get host IP by name
struct hostent *host;
host = gethostbyname(req.GetHost().c_str());
//Setup remote address structure
struct sockaddr_in remoteAddr;
remoteAddr.sin_family = AF_INET;
remoteAddr.sin_port = htons(req.GetPort());
remoteAddr.sin_addr = *((struct in_addr *)host->h_addr);
//create new socket for remote server
int remoteSock = socket(AF_INET, SOCK_STREAM, 0);
if(remoteSock < 0)
{
perror("Socket Error");
//return -1;
}
//connecting to remote server
if(connect(remoteSock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0)
{
perror("Connect Error");
//return -1;
}
cout.flush() << requestBuf << endl;
//send request to remote server
if(send(remoteSock, requestBuf, sizeof(requestBuf), 0) < 0)
{
perror("Write Error");
//return -1;
}
//receive reply from server
char *recBuf = new char [1024];
int bufSize = 1024;
int readSize;
while(1)
{
readSize = read(remoteSock, recBuf, bufSize); //Read from Remote Server
cout.flush() << recBuf << endl;
if(readSize <= 0) //If the requestBuf not filled, nothing left to send to client
break;
write(clientSock, recBuf, readSize); //write reply to Client
}
close(remoteSock);
recBuf 的 cout.flush() 什么也不输出。
关于发生了什么的任何想法?