gpt4 book ai didi

c - 服务器端输出奇怪的字符

转载 作者:行者123 更新时间:2023-11-30 16:56:08 25 4
gpt4 key购买 nike

当我将输出文件从客户端发送到服务器时,我的输出文件中有一堆奇怪的字符。当我将服务器流式传输到数组并将其打印出来时,它看起来不错且清晰。然而,当我将其发送到服务器时,我在文本文档中到处都看到了一堆奇怪的字符和 MICROSOFT。有人知道出了什么问题吗?

客户:

if(sendSize <=0){
for(;;){
unsignedchar buff[256]={0};
int nread = fread(buff,1,256, fp);

total = total + nread;
percentage =(total / fFileSize)*100;
printf("\r%s: Percentage sent: %.2f", NAME_C, percentage);
/* Send data in 256 byte chunks */
if(nread >0){
send(clientSock, buff, nread, 0);
}

if(nread <256){
if(feof(fp)){
printf("\nSend Success!\n");
break;
}
}
}
//printf("%.2f", total);
}

服务器:

/* Receive data from client */
char* fileName ="test.txt";
FILE*fp = fopen(fileName,"w+");;

float total =0;
float bytesReceived;
unsignedchar buff[256]={0};
float percentage =(bytesReceived / total)*100;

while((bytesReceived = recv(listenSock, buff,sizeof(buff),0))<0){
//bytesReceived = recv(listenSock, buff, 256, 0);
if(bytesReceived >0){
printf("DONE");
}
//total = total + bytesReceived;
fwrite(buff,sizeof(char), bytesReceived, fp);
//printf("\r%s: Percentage received: %.2f", NAME_C, percentage);
}

最佳答案

您的服务器的recv()循环正在使用 <0什么时候应该使用 >0反而。 recv()出错时返回 -1,正常断开连接时返回 0,收到字节时返回 >0。

另外,是listenSock实际监听的套接字,或者 accept() 返回的套接字?您应该将后者传递给 recv() 。我的猜测是你正在传递前者,导致 recv()失败并返回 -1,然后使用垃圾 buff 进入循环体数据又不好bytesReceived值(value)。第三个参数fwrite()size_t ,这是一个无符号类型,因此传递 -1 有符号值将被解释为 4294967295 的无符号值甚至 18446744073709551615 ,取决于 size_t 的大小。无论哪种方式,您都会向文件中写入垃圾,甚至会导致尝试访问无效内存的代码崩溃。

您的代码还存在其他小问题。尝试更像这样的东西:

客户:

if(sendSize <=0){
unsigned char buff[256];
do{
int nread = fread(buff, sizeof(char), 256, fp);
if (nread > 0){
total += nread;
percentage = (total / fFileSize)*100;
printf("\r%s: Percentage sent: %.2f", NAME_C, percentage);
/* Send data in 256 byte chunks */
if (send(clientSock, buff, nread, 0) == -1){
printf("\nSend Failed!\n");
break;
}
}
if (nread != 256){
if (feof(fp)){
printf("\nSend Success!\n");
else
printf("\nRead Failed!\n");
break;
}
}
while (1);
//printf("%.2f", total);
}

服务器:

/* Receive data from client */
char* fileName = "test.txt";
FILE* fp = fopen(fileName, "wb+");
if (!fp){
printf("\nOpen Failed!\n");
}
else{
float total = 0;
float percentage = 0;
int bytesReceived;
unsigned char buff[256];

do{
bytesReceived = recv(acceptedSock, buff, sizeof(buff), 0);
if (bytesReceived <= 0){
if (bytesReceived < 0){
printf("\nRecv Failed!\n");
}
else{
printf("\nDisconnected!\n");
}
break;
}
//total += bytesReceived;
//percentage = ...
if (fwrite(buff, sizeof(char), bytesReceived, fp) != bytesReceived){
printf("\nWrite Failed!\n");
break;
}
//printf("\n%s: Percentage received: %.2f", NAME_C, percentage);
}
while (1);
}

关于c - 服务器端输出奇怪的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40049925/

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