当前位置: 技术问答>linux和unix
用socket与http服务器通信的问题
来源: 互联网 发布时间:2015-11-16
本文导语: 请高手帮忙,下面的代码为什么服务器没响应,ReadLine()函数读完后是空串? (注:site_name 和 path_name经其它程序测试过,正常) #include #include #include #include #include /* gethostbyname() */ #define RECV_BUF_SIZE 512 #define SEND_BUF...
请高手帮忙,下面的代码为什么服务器没响应,ReadLine()函数读完后是空串?
(注:site_name 和 path_name经其它程序测试过,正常)
#include
#include
#include
#include
#include /* gethostbyname() */
#define RECV_BUF_SIZE 512
#define SEND_BUF_SIZE 512
struct sockaddr_in a;
unsigned short port = 80;
char site_name[256] = "www.maketop.net";
char path_name[256] = "/resource/rs_041112_02.php";
int ConnectToServer(char *url,int *sfd);
int main(int argc, char *argv[])
{
int sockfd;
char send_buf[SEND_BUF_SIZE];
char recv_buf[RECV_BUF_SIZE];
ConnectToServer(site_name,&sockfd);
sprintf(send_buf,
"GET %s HTTP/1.0rn",path_name);
ksend(sockfd,send_buf,strlen(send_buf),0);
ReadLine(sockfd,recv_buf);
printf("%sn",recv_buf);
close(sockfd);
return 0;
}
int ReadLine(int sfd,char *l)
{
int i=0;
do
{
if(buf_readchar(sfd,l+i)h_addr))->s_addr;
/* to connect ! */
if(connect(*sfd, (struct sockaddr *)&a, sizeof(a)) == -1)
{
printf("connect to server failedn");
close(*sfd);
exit(1);
}
printf("connect to server succeededn");
return 0;
}
int ksend(int sfd,char *buf,int length,int flag)
{
int a;
a = send(sfd,buf,length,0);
if(a == -1)
{
fprintf(stderr,"send message failedn");
exit(1);
}
return 0;
}
int buf_readchar(int fd, char *ret)
{
int res;
res = recv(fd, ret, 1, 0);
if (res
(注:site_name 和 path_name经其它程序测试过,正常)
#include
#include
#include
#include
#include /* gethostbyname() */
#define RECV_BUF_SIZE 512
#define SEND_BUF_SIZE 512
struct sockaddr_in a;
unsigned short port = 80;
char site_name[256] = "www.maketop.net";
char path_name[256] = "/resource/rs_041112_02.php";
int ConnectToServer(char *url,int *sfd);
int main(int argc, char *argv[])
{
int sockfd;
char send_buf[SEND_BUF_SIZE];
char recv_buf[RECV_BUF_SIZE];
ConnectToServer(site_name,&sockfd);
sprintf(send_buf,
"GET %s HTTP/1.0rn",path_name);
ksend(sockfd,send_buf,strlen(send_buf),0);
ReadLine(sockfd,recv_buf);
printf("%sn",recv_buf);
close(sockfd);
return 0;
}
int ReadLine(int sfd,char *l)
{
int i=0;
do
{
if(buf_readchar(sfd,l+i)h_addr))->s_addr;
/* to connect ! */
if(connect(*sfd, (struct sockaddr *)&a, sizeof(a)) == -1)
{
printf("connect to server failedn");
close(*sfd);
exit(1);
}
printf("connect to server succeededn");
return 0;
}
int ksend(int sfd,char *buf,int length,int flag)
{
int a;
a = send(sfd,buf,length,0);
if(a == -1)
{
fprintf(stderr,"send message failedn");
exit(1);
}
return 0;
}
int buf_readchar(int fd, char *ret)
{
int res;
res = recv(fd, ret, 1, 0);
if (res