I’ve made a simple tcp server/client app where the client writes something to the server and it’s then echoed back to the client. However, i’m having some problems when i’m trying to read what the server echoed back in the client.
string s;
while((n = read(socketFD[0],readBuf, BUFFER_SIZE)) > 0){
cout<<"\nBytes read: "<<n<<endl;
s.append(readBuf, n);
}
cout<<"\nTest after read\n";
I write 16 KB of text to the server. When i’m reading in the client I read 4 KB at a time.
The output from this code is:
Bytes read: 4096
Bytes read: 4096
Bytes read: 4096
Bytes read: 4046
The read call seem to block after it’s done reading from the socket and never leave the loop. How can I fix this?
EDIT: This is the code in the server that handles connected clients.
if((childpid = fork()) == 0){
close(listenFD);
while ((n = read(connectFD, buf, BUFFSIZE)) > 0){
cout<<"\nBytes read: "<<n<<endl;
write(connectFD, buf, n);
}
cout<<"\nTest after read\n";
exit(0);
}
This output is:
Bytes read: 4096
Bytes read: 4096
Bytes read: 4096
Bytes read: 4046
Test after read
What’s different here compared to the code in the client? Why doesn’t the read call block as it does in the client?
Short answer, don’t call
readafter you’re received all the data.Write code to detect when you’ve received all the data you want to receive at that time and, if so, exit the loop. You have to actually implement some kind of protocol.
That can’t be right. How does it know how many bytes of data to add to
s?