more refactor, print error message *if* there is one, and RFC compliance (terminating connection after sending quote)

This commit is contained in:
Arthur-Coppey 2021-11-26 14:08:49 +01:00
parent b869bbbc27
commit 5459693777

View File

@ -10,22 +10,22 @@
extern int errno; extern int errno;
_Noreturn void udpListen(int serverSocket, struct sockaddr * clientAddress, unsigned long addressLength) { _Noreturn void udpListen(int serverSocket, struct sockaddr * clientAddress, unsigned long addressLength) {
int recvLen;
char clientMessage[MESSAGE_STRING_LENGTH], quote[MESSAGE_STRING_LENGTH]; char clientMessage[MESSAGE_STRING_LENGTH], quote[MESSAGE_STRING_LENGTH];
for (;;) { for (;;) {
// receive data // receive data
recvLen = recvfrom(serverSocket, clientMessage, MESSAGE_STRING_LENGTH, 0, clientAddress, (socklen_t *) &addressLength);
perror("recvfrom"); if (recvfrom(serverSocket, clientMessage, MESSAGE_STRING_LENGTH, 0, clientAddress, (socklen_t *) &addressLength) >= 0) {
if (recvLen >= 0) { printf("received: %s\n", clientMessage);
printf("client says: %s\n", clientMessage);
// send data // send data
getRandomQuote(quote); getRandomQuote(quote);
printf("responding: `%s`\n", quote); printf("sending: %s\n", quote);
sendto(serverSocket, quote, strlen(quote), 0, clientAddress, addressLength); if (sendto(serverSocket, quote, strlen(quote), 0, clientAddress, addressLength) == -1) {
perror("sendto"); perror("udp: sendto");
}
} else {
perror("udp: recvfrom");
} }
} }
} }
@ -39,21 +39,26 @@ void tcpListen(int serverSocket, struct sockaddr * clientAddress, unsigned long
// accept connections // accept connections
//TODO: t h r e a d s //TODO: t h r e a d s
while ((clientSocket = accept(serverSocket, clientAddress, (socklen_t *) &addressLength)) >= while ((clientSocket = accept(serverSocket, clientAddress, (socklen_t *) &addressLength)) >= 0) {
0) {
puts("client connected"); puts("client connected");
// receive data // receive data
while (recv(clientSocket, clientMessage, MESSAGE_STRING_LENGTH, 0) >= 0) { if (recv(clientSocket, clientMessage, MESSAGE_STRING_LENGTH, 0) >= 0) {
printf("client says: %s\n", clientMessage); printf("client says: %s\n", clientMessage);
// send data // send data
getRandomQuote(quote); getRandomQuote(quote);
printf("responding: \"%s\"\n", quote); printf("responding: \"%s\"\n", quote);
send(clientSocket, quote, strlen(quote), 0); if (send(clientSocket, quote, strlen(quote), 0) == -1) {
perror("tcp: send");
}
} else {
perror("tcp: recv");
} }
puts("client disconnected"); close(clientSocket);
puts("closed connection");
} }
if (clientSocket < 0) { if (clientSocket < 0) {