I have a read/write loop between a client and a server on a TCP socket, and I can't see why the loop is being gone through twice for every write from the client?
For every message that is entered by the client, the server loops through twice up until the second write.
Server:
1 2 3 4 5 6 7 8 9 10
again:
while((bytes_read = read(newsockfd, data, 50))>0) { // read from client
if (bytes_read < 0 && errno == EINTR)
goto again;
elseif (bytes_read < 0)
cerr<<"read error"<<endl;
data[bytes_read]='\0';
cout<<data<<endl; // print message
write(newsockfd, data, bytes_read); // Write the buffer to the client
}
Client:
1 2 3 4 5 6 7 8 9 10 11 12 13
while(cin.getline(sendbuf, 100)!=NULL) { // get message from stdin
cin.clear();
if((nbytes = write(sfd, sendbuf,100))==-1) { // write message to server
cout<<"Write error"<<endl;
exit(1);
}
if((nbytes=read(sfd,recv, 100))==-1) { // read message from server
cout<<"Read error"<<endl;
exit(1);
}
recv[nbytes]='\0';
cout<<recv<<endl; // print message to stdout
}