gpt4 book ai didi

c套接字: send() send only 1 byte at a time

转载 作者:行者123 更新时间:2023-11-30 19:11:39 29 4
gpt4 key购买 nike

我有以下程序,它必须一次读取 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.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;
}

发送函数定义为:

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;
}
}
}

其中 Socket 是指向包含套接字文件描述符和其他信息的结构的指针。

我尝试在每次迭代时打印 nsent,并且发现套接字发送函数一次仅发送 1 个字节,因此传输 1MB 需要花费大量时间。

可能是哪个问题?

最佳答案

您将值1(n的值)作为buflen传递到Send中,所以它一次只发送一个字节。

如果n是兆字节数,则调用该函数时需要将该值乘以1048576:

Send(socket, buffer, n * 1048576);

关于c套接字: send() send only 1 byte at a time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39472948/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com