c socket:send()一次只发送1个字节
我有以下程序,必须一次读取1MB的文件,将其发送到服务器(每次总是1MB),然后返回哈希代码:c socket:send()一次只发送1个字节,c,sockets,C,Sockets,我有以下程序,必须一次读取1MB的文件,将其发送到服务器(每次总是1MB),然后返回哈希代码: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "Socket.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "Socket.h"
#include "../utils.h"
char *prog_name;
int main (int argc, char *argv[])
{
int fd, hash, n=atoi(argv[3]);
char buffer[1048576];
Socket socket=SCreate(TCP);
Connect(socket, argv[1], atoi(argv[2]));
fd=open(argv[4], O_RDONLY);
if(read(fd, buffer, 1048576)<1048576)
return 1;
while(n>0) {
Send(socket, buffer, n);
read(fd, buffer, 1048576);
n--;
}
RecvN(socket, &hash, 4);
printf("%d", ntohl(hash));
return 0;
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括“Socket.h”
#包括“./utils.h”
字符*程序名;
int main(int argc,char*argv[])
{
int fd,hash,n=atoi(argv[3]);
字符缓冲区[1048576];
套接字=创建(TCP);
连接(套接字,argv[1],atoi(argv[2]);
fd=打开(argv[4],仅限Ordu);
if(读取(fd,缓冲器,1048576)0){
发送(套接字、缓冲区、n);
读取(fd,缓冲器,1048576);
n--;
}
RecvN(套接字和散列,4);
printf(“%d”,ntohl(散列));
返回0;
}
发送功能定义为:
void Send(Socket socket, void *buffer, int buflen) {
int nleft, nsent;
for(nleft=buflen; nleft>0;) {
if((nsent=send(socket->sockfd, buffer, nleft, 0))<=0) {
perror("Send error");
exit(-1);
} else {
nleft-=nsent;
buffer+=nsent;
}
}
}
void发送(套接字、void*缓冲区、int buflen){
int nleft,nsent;
对于(nleft=buflen;nleft>0;){
如果((nsent=send(socket->sockfd,buffer,nleft,0))您将值1
(值n
)作为buflen
传入send
,那么它一次只发送一个字节
如果n
是兆字节数,则调用函数时需要将该值乘以1048576:
Send(socket, buffer, n * 1048576);
显示用于启动程序的命令行../a.out 127.0.0.1 1994 1.././tools/big_file.txt;因此argv[1]是服务器IP,argv[2]是服务器端口,argv[3]是从文件中读取的MB数,argv[4]是文件名n=atoi(argv[3])
,这是传递给Send()
asbuflen
。我想你忘了把它乘以1024*1024
。你是对的。愚蠢的错误。谢谢。