Gomathi
Gomathi

Reputation: 1003

Error in read and write client server programming

I'm working on a c program in linux. I need to use client server programming. I used read and write and it worked fine. But after using more than 20 read and write in both server and client, it has stopped working. That is I don't receive any output for that. Line. I don't understand what is the problem because am using the very same lines.

bzero(&hl,200);
read(a,hl,50*sizeof(char));
printf("%s",hl);

In client side,

bzero(&hl,200);
strcpy(hl,"hello");
write(a,hl,50*sizeof(char));
printf("%s",hl);

Also, am not able to get the return value and print it. While I used it in debian, I got the return value and able to print. Now, am in Ubuntu (at home). It's not printing return value now. No error too! Is it anything to do with OS?

Please help me figure out the problem.

UPDATED:

In server,

int c: s=read(a,&c,sizeof(int)); printf("choice: %d",c);

In client,

scanf("%d",&ch); s=write(sd,&ch,sizeof(int));

Both has size 4. But, in client I got garbage value while I print the choice.

Upvotes: 0

Views: 152

Answers (1)

David Schwartz
David Schwartz

Reputation: 182865

You throw away the return value of read, so you have no idea how many bytes you've read. What if it's less than 50?

Change:

read(a,hl,50*sizeof(char));

To:

int readBytes = 0;
do
{
    int r = read(a, hl + readBytes, 50 - readBytes);
    if (r <= 0)
        return; // or however you want to handle an error
    readBytes += r;
} while (readBytes < 50);

That will ensure you actually read 50 bytes.

You are imagining that TCP somehow "glues" those 50 bytes together. But the system has no idea that those 50 bytes are a message -- only your code does. So it's your code's job to glue them back together. TCP does not preserve application message boundaries -- that is the application's job.

Upvotes: 1

Related Questions