#define PORT 3490
struct frame
{
int frame_seq;
void *date;
int frame_date_len;
};
int main(int argc, char *argv[])
{
int sockfd,numbytes;
struct hostent *he;
struct sockaddr_in their_addr;
struct frame send_frame;
int num=0;
if(argc!=2)
{
fprintf(stderr,"usage:client hostname\n");
exit(1);
}
if((he=gethostbyname(argv[1]))==NULL)
{
herror("gethostbyname");
exit(1);
}
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("socket");
exit(1);
}
int opt=SO_REUSEADDR; //设置套接字为地址重用方式
setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
memset(&their_addr,0,sizeof(their_addr));
their_addr.sin_family=AF_INET;
their_addr.sin_port=htons(PORT);
//their_addr.sin_addr=*((struct in_addr *)he->h_addr);
their_addr.sin_addr.s_addr = inet_addr("192.168.9.140");
//bzero(&(their_addr.sin_zero),8);
if(connect(sockfd,(struct sockaddr *)&their_addr,sizeof(struct sockaddr))==-1)
{
perror("connect");
exit(1);
}
char buf[50<<10]="";
fd_set wfd;
struct timeval timeout;
int send_len=0, buf_len=0;
int ret;
do
{
send_frame.frame_date_len = random()%(20<<10);
send_frame.frame_seq = num++;
send_frame.date=malloc(send_frame.frame_date_len);
memcpy(buf,(char *)&send_frame,sizeof(send_frame));
do
{
timeout.tv_sec=10;
timeout.tv_usec=0;
FD_ZERO(&wfd);
FD_SET(sockfd,&wfd);
ret=select(sockfd+1, NULL, &wfd, NULL, &timeout);
if(ret == -1)
{
perror("select");
}
else if(ret == 0)
{
printf("send date time out.\n");
exit(0);
}
else
{
if( FD_ISSET(sockfd,&wfd) )
{
buf_len = send_frame.frame_date_len - send_len;
if((numbytes=send(sockfd, buf+send_len, buf_len, 0))==-1)
{
perror("send");
exit(1);
}
else
printf("frame_seq=%d,send date=%d,frame_date_len=%d\n",send_frame.frame_seq,numbytes,send_frame.frame_date_len);
send_len = send_len+numbytes;
}
else
exit(1);
}
}while( send_len < send_frame.frame_date_len );
usleep(40000);
free(send_frame.date);
//memset(&buf,0,sizeof(buf));
}while(1);
close(sockfd);
return 1;
}
如上程序,发送一个数据结构体,一直出现发送数据不对,求解。 |