开发者

Only first byte is received when sending string from client to server

I made a client/server program and am sending a file from the client to the server.

Here is a piece of the code:

Client side:

FILE *f = fopen("file.txt" ,"r");
size_t bytes = 0;
while(bytes = fr开发者_Go百科ead(buffer ,sizeof(char) , sizeof(buffer) ,f)>0)
{printf("buff%s\n" , buffer);
send(sockfd ,buffer ,bytes , 0);
} 
fclose(f);
  printf("%s\n",buffer);

Server side:

FILE *f = fopen("file1.txt" ,"w");
while(bytes = recv(newsockfd ,buffer , sizeof(buffer) ,0)>0)
{
printf("bytes%d" , bytes);
fwrite(buffer,sizeof(char) ,bytes , f);
}
bytes = recv(newsockfd ,buffer , sizeof(buffer) ,0);
printf("bytessss%d" , bytes);
  fclose(f);  
     printf("Here is the message: %s\n",buffer);
     close(newsockfd);

But when I send it to the server, the server makes a file and stores only the first byte, eg when I send "hi whats up ", the server only stores "h".


You miss one parenthesis:

while(bytes = recv(newsockfd ,buffer , sizeof(buffer) ,0) > 0)

which make bytes variable 1 or 0, because the expression is calculated as recv(newsockfd ,buffer , sizeof(buffer) ,0) > 0 although the number of bytes read is the correct one. Add the parenthesis like that:

while ((bytes = recv(newsockfd ,buffer , sizeof(buffer) ,0)) > 0)
       ^                                                   ^

Missed that, but the same applies to your client, you read all the bytes to the buffer, but the bytes variable is again assigned with 1, since

while(bytes = fread(buffer ,sizeof(char) , sizeof(buffer) ,f)>0)

is evaluated this way:

while(bytes = (fread(buffer ,sizeof(char) , sizeof(buffer) ,f)>0) )
               ^
               1. call fread, keep the result in temporary place (let's call it X)
                                                              ^
                                                    2. compare "x" to 0
            ^
            3. store result of comparison (instead of fread) in the variable bytes.

meaning, read sizeof(buffer) bytes from the file, if the number of bytes read are bigger than 0, put 1 into bytes, else put 0 (the result of boolean expression is either 1 (true) or 0 (false)), so even if you read 100 bytes, the buffer is indeed filled with them, but the bytes variable is equal to 1 so you send 1 byte. when you attempt to read again, there's nothing to read, since last time you already read 100 bytes. The extra parenthesis makes it first to assign the number of bytes read to bytes variable and only then compare it to 0:

while((bytes = fread(buffer ,sizeof(char) , sizeof(buffer) ,f))>0)


As the previous answer explains, precedence rule is the one and only problem in your code.

> has higher precedence than =.

I think first 2 answers for the below given question will help you....

C write() function not working

I think that guy had a same problem as like you....

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜