I am just learning socket programming and I am trying to write an echo client that reads from stdin and writes to a socket and then reads the server response from the socket to stdout. The problem is that I don’t know how long stdin will be or how long the server’s response will be. The code I am trying to use is as follows (creating the socket and connecting to the server are left out):
length = BUF_SIZE;
while (length == BUF_SIZE) { // length will equal BUF_SIZE if buf is full, when length < BUF_SIZE we have reached an EOF
// Reads from STDIN to buf
if ((length = read(STDIN_FILENO, buf, BUF_SIZE)) < 0){
fprintf(stderr, "Error in reading from STDIN");
return 4;
}
// Writes from buf to the socket
if ((write(sock, buf, BUF_SIZE)) < 0){
fprintf(stderr, "Error writing to socket");
return 5;
}
}
if ((status = shutdown(sock, 1)) < 0){ // Shuts down socket from doing more receives
fprintf(stderr, "Error shutting down socket for writing");
return 6;
}
length = BUF_SIZE;
while (length == BUF_SIZE){
// Read from socket to buf
if ((length = read(sock, buf, BUF_SIZE)) < 0){
fprintf(stderr, "Error reading from socket");
return 7;
}
// Write from buf to STDOUT
if ((write(STDOUT_FILENO, buf, BUF_SIZE)) < 0){
fprintf(stderr, "Error writing to STDOUT");
return 8;
}
}
close(sock);
exit(0);
BUF_SIZE is defined as 100. When I run my program the program typically connects to the server and sends the proper message, but what it writes to stdout is either nothing or gibberish.
What am I doing wrong?
Your while loop is only going to work the first time through. read()/write() are only going to return the amount that they actually read/write which may well not be equal to BUF_SIZE. Let’s say you read ten bytes from the socket and then you write a hundred to stdout – the last 90 are going to be garbage.
Something along these lines will get you somewhat closer to what you want.