C读取网页

#define _WIN32_

#ifdef _WIN32_

#include
<winsock2.h>
#include
<windows.h>
#include
<memory.h>
#include
<stdio.h>
#include
<string.h>
#include
<pthread.h>
#include
<assert.h>
#include
<pcre.h>

#pragma comment(lib, "pthreadVC2.lib")
#pragma comment(lib, "ws2_32.lib")

#else

#endif//_WIN32_

#define DBG 1
#define SERVPORT 80
#define MAXDATASIZE 99999 /*每次最大数据传输量 */

char buf[MAXDATASIZE];
char header[300] ="";
int sockfd,wsastat,server_ip,error;


void get_msg(void){

while( (recv( sockfd, buf, MAXDATASIZE, 0 )) >0){

FILE
*fp;

if ( (fp = fopen( "1.txt", "w+" )) !=NULL ){

if ( (fputs(buf,fp)) != EOF ){
printf(
"write~^_^");
}
else{
printf(
"write~ - -");
}

}
else{

printf(
"........");

}

fclose(fp);
}
}



int create_pthread(){

pthread_t pid;
pthread_attr_t attr;
pthread_attr_init(
&attr );
pthread_attr_setscope(
&attr, PTHREAD_SCOPE_PROCESS );
pthread_attr_setdetachstate(
&attr, PTHREAD_CREATE_DETACHED );
pthread_create(
&pid, &attr, get_msg, NULL );

}

void proc_main(){

/* host name */
char*domain ="trading.5173.com";
static WSADATA wsa_data;
struct hostent *host;
struct sockaddr_in serv_addr;

strcat(header,
"GET ");

strcat(header,
"/search/b2062182a4384f2dbbe18479d86138d9.shtml?");
strcat(header,
"cate=72288cb9cc334746920897b9095fd7ad&basictype=0");
strcat(header,
"&ga=e2c6bab2de7647a3990a8f6d87b7f71d");
strcat(header,
"&gs=d8d1b31d0cfd43ed90c1194b1e10f0ba");

strcat(header,
" HTTP/1.1\r\n");
strcat(header,
"HOST: ");
strcat(header, domain);

/*
strcat(header, "\r\nConnection: Close\r\n\r\n"); //连接一次则关闭SOCk
*/

strcat( header,
"\r\nConnection: keep-alive\r\n\r\n" );//长连接

wsastat
= WSAStartup(MAKEWORD(2,2), &wsa_data);

if( wsastat !=0x00000000 ){// 初始化失败

printf(
"create a socket it's fill");
system(
"pause");

}

memset(
&serv_addr,0,sizeof(struct sockaddr) );

if ( DBG==0 ){

char hostname[128];
gethostname( hostname,
127 );
host
= gethostbyname(hostname);

}
else{
host
= gethostbyname(domain);

}

memcpy(
&server_ip, host->h_addr_list[0], sizeof(host->h_addr_list[0]) );

if( host==NULL ){

error
= WSAGetLastError();
printf(
"%d",error);
system(
"pause");

}

if ( ( sockfd = socket( AF_INET, SOCK_STREAM, 0 ) ) ==-1 ){

printf(
"socket create error!");
system(
"pause");


}

serv_addr.sin_family
= AF_INET;
serv_addr.sin_port
= htons(SERVPORT);
serv_addr.sin_addr.s_addr
= server_ip;


if ( connect( sockfd, (struct sockaddr *) &serv_addr,sizeof(struct sockaddr) ) <0 ) {

printf(
"conntion server invalid!error code:%d\n", WSAGetLastError() );
system(
"pause");

}
else{

printf(
"conntion server ok!code:%d\n",WSAGetLastError());
printf(
"wait message for server!.....\n");
}

create_pthread();

while(1){


send( sockfd, header, strlen(header),
0 );
printf(
"HOST:%s \n",domain);
Sleep(
30*1000);
system(
"cls");

}

}

main(
void){

proc_main();
system(
"pause");

}
posted @ 2011-04-20 00:01  方东信  阅读(524)  评论(0编辑  收藏  举报