SOCKET 接受到的文件总是少了一个字节
今天写了一个SOCKET程序。期望:向服务端(不用考虑实现)发起一个连接,并且向服务端发送一个XML文件,然后服务端返回一个XML文件。
大体上实现了上述功能。
但重点来了:
我接受到的XML文件总是少了一个字节。
今天下午抓包看了,服务端传过来的数据是完整的。
我的代码:
程序代码:
#include<netinet/in.h> #include<sys/types.h> #include<sys/socket.h> #include<stdio.h> #include<stdlib.h> #include<string.h> #define MYPORT 1029 #define BUFFERSIZE 1024 int main(int argc,char **argv) { if(argc!=2) { printf("argc<2\n"); exit(1); } struct sockaddr_in client_addr; bzero(&client_addr,sizeof(client_addr)); client_addr.sin_family=AF_INET; client_addr.sin_addr.s_addr=htons(INADDR_ANY); client_addr.sin_port=htons(0); int client_socket=socket(AF_INET,SOCK_STREAM,0); if(client_socket<0) { printf("Create Socket Failed!\n"); exit(1); } if(bind(client_socket,(struct sockaddr *)&client_addr,sizeof(client_addr))) { printf("Client Bind Port Failed!\n"); exit(1); } struct sockaddr_in server_addr; bzero(&server_addr,sizeof(server_addr)); server_addr.sin_family=AF_INET; if(inet_aton(argv[1],&server_addr.sin_addr)==0) { printf("Server IP Address Error!\n"); exit(1); } server_addr.sin_port=htons(MYPORT); socklen_t server_addr_length=sizeof(server_addr); if(connect(client_socket,(struct sockaddr *)&server_addr,server_addr_length)<0) { printf("Can Not Connect To %s!\n",argv[1]); exit(1); } char buf[BUFFERSIZE]; FILE *fp_1=fopen("send.xml","r"); if(fp_1==NULL) { printf("File not found!\n"); } else { bzero(buf,BUFFERSIZE); int file_block_length=0; while((file_block_length=fread(buf,sizeof(char),BUFFERSIZE,fp_1))>0) { printf("flie_block_length=%d\n",file_block_length); if(send(client_socket,buf,file_block_length,0)<0) { printf("Send file failed!\n"); break; } bzero(buf,sizeof(buf)); } fclose(fp_1); printf("Finished!\n"); } FILE *fp=fopen("test.xml","w"); if(fp==NULL) { printf("Can Not Open To Write!\n"); exit(1); } bzero(buf,sizeof(buf)); int length=0; while(length=recv(client_socket,buf,BUFFERSIZE,0)) { if(length<0) { printf("Receive Data Failed!\n"); break; } int write_length=fwrite(buf,sizeof(char),length,fp); if(write_length<length) { printf("Write Failed!\n"); break; } bzero(buf,BUFFERSIZE); } printf("Success!\n"); fclose(fp); close(client_socket); return 0; }
大家帮忙啊!!!