diff --git a/echoserver/echoserver.c b/echoserver/echoserver.c index f41f986..a4ad02d 100644 --- a/echoserver/echoserver.c +++ b/echoserver/echoserver.c @@ -16,7 +16,9 @@ int main(int argc, char **argv) bool quitFlag = true; int socketEchoFD; int clientEchoFD; + int reuseAddrOpt = 1; char message[BUFFER_SIZE]; + int messageBytes; struct sockaddr_in serverAddr; struct sockaddr_storage clientAddr; socklen_t clientSize; @@ -30,6 +32,9 @@ int main(int argc, char **argv) return -1; } // use the setsockopt function to make the socket accept different configurations + // allow for the reuse of the address/bind. + setsockopt(socketEchoFD, SOL_SOCKET, SO_REUSEADDR, &reuseAddrOpt, sizeof(reuseAddrOpt)); + // also need to set the socket to non-blocking using setsockopt? // CODE HERE // bind the TCP socket to port 8888 / ECHOPORT serverAddr.sin_family = AF_INET; @@ -82,7 +87,7 @@ int main(int argc, char **argv) return -1; } // grab the data from the client, save to message. - // NEW CODE HERE + messageBytes = recv(clientEchoFD, message, BUFFER_SIZE, MSG_WAITALL); // if "01189998811991197253\r\n" is received, then close the server. if (strcmp(message, "01189998811991197253\n") == 0 || strcmp(message, "01189998811991197253\r\n") == 0) { @@ -92,6 +97,17 @@ int main(int argc, char **argv) } // otherwise, repeat/echo back the message to the client. // NEW CODE HERE + // make sure that the connection is still open before attempting to send. + if(messageBytes <= 0) + { + // this means that the connection is closed, or had another error. + return -1; + } + else + { + // send back the message over the clientEcho socket. + send(clientEchoFD, message, messageBytes, 0); + } // close the accepted listening socket since it is no longer needed. close(clientEchoFD); }