实现对HTTP协议工作过程的模拟

#include <iostream>
#include <cstring>
#include <string>
#include <Winsock2.h>
#pragma comment(lib,"Ws2_32.lib")
using namespace std;

int main(){
 SOCKET sock;
 sockaddr_in addrSrv;
 string host="www.sina.com.cn";
 hostent *haddr;
 bool label=false;
 int num=0;
 int jmp;
 string content;
 char *buffer=new char[1024];
 content.empty();
 WSADATA wsadata;
 FILE *fp=fopen("./temp.html","a+");

 if(WSAStartup(MAKEWORD(1,1),&wsadata)!=0){
  cout<<"WSAStartup() error!"<<endl;
  return 0;
 }
 if(LOBYTE(wsadata.wVersion)!=1||HIBYTE(wsadata.wVersion)!=1){
  WSACleanup();
  cout<<"WSAStartup() error!"<<endl;
  return 0;
 }

 if((sock=socket(AF_INET,SOCK_STREAM,0))==-1){
  cout<<"socket() error!"<<endl;
  return 0;
 }
 if((haddr=gethostbyname(host.c_str()))==NULL){
  cout<<"gethostbyname() error!"<<endl;
  return 0;
 }
 addrSrv.sin_addr=*((struct in_addr *)*(haddr->h_addr_list));
 //cout<<inet_ntoa(addrSrv.sin_addr)<<endl;
 addrSrv.sin_family=AF_INET;
 addrSrv.sin_port=htons(80);

 if(connect(sock,(sockaddr *)&addrSrv,sizeof(addrSrv))==-1){
  cout<<"connect() error!"<<endl;
  return 0;
 }

 send(sock,"GET / HTTP/1.1\r\n",strlen("GET / HTTP/1.1\r\n"),0);
 send(sock,"Host:222.25.185.203\r\n",strlen("Host:222.25.185.203\r\n"),0);
 send(sock,"Accept:application/x-coment,image/gif,image/x-xbitmap,image/jpg,image/pjpeg,*/*\r\n",strlen("Accept:application/x-coment,image/gif,image/x-xbitmap,image/jpg,image/pjpeg,*/*\r\n"),0);
 send(sock,"User-Agent:Mozilla/4.0\r\n",strlen("User-Agent:Mozilla/4.0\r\n"),0);
 send(sock,"Connection:Keep-Alive\r\n",strlen("Connection:Keep-Alive\r\n"),0);
 send(sock,"\r\n",strlen("\r\n"),0);
 send(sock,"\r\n",strlen("\r\n"),0);//添加两个回车换行

 jmp=0;
 while(!label){
  num=recv(sock,buffer,1,0);
  content+=*buffer;
  if(num<0){
   label=true;
  }
  switch(*buffer){
  case '\r':
   break;
  case '\n':
   if(jmp==0)
    label=true;
   jmp=0;
   break;
  default:
   jmp++;
   break;
  }
  //cout<<buffer[0];
 }
 cout<<content;
 do{
  memset(buffer,'\0',1024);
  num=recv(sock,buffer,1024,0);
  if(num<0)
   break;
  //content+=buffer;
  content.append(buffer);
  fwrite(buffer,strlen(buffer),1,fp);
  //fputs(buffer,fp);
  //cout<<buffer;
 }while(num>0);
 closesocket(sock);

 if(WSACleanup()!=0){
  cout<<"WSACleanup() error!"<<endl;
 }
 //cout<<content<<endl;
 fclose(fp);
 ShellExecute(NULL,"open",".\\temp.html",NULL,NULL,SW_SHOWNORMAL);
 return 0;
}

 

你可能感兴趣的:(工作,socket,null,buffer,include,FP)