Commit 5e108d86 authored by Maxime POULAIN's avatar Maxime POULAIN
Browse files

fix server crashing at client exit

parent 09fff080
No preview for this file type
...@@ -10,8 +10,6 @@ ...@@ -10,8 +10,6 @@
#include "bool.h" #include "bool.h"
void start(int port) { void start(int port) {
bool needToStop = false;
int server_fd, new_socket, valread; int server_fd, new_socket, valread;
struct sockaddr_in address; struct sockaddr_in address;
int opt = 1; int opt = 1;
...@@ -44,21 +42,33 @@ void start(int port) { ...@@ -44,21 +42,33 @@ void start(int port) {
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
printf("Listening on port %d\n", port); printf("Listening on port %d\n", port);
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
while (!needToStop) {
memset(bufferIn, 0, BUFFER_SIZE);
memset(bufferOut, 0, BUFFER_SIZE);
recv(new_socket, bufferIn, BUFFER_SIZE, 0); while (true) {
handleClientRequest(bufferIn, bufferOut);
printf("CLIENT : %s\n",bufferIn); if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen)) < 0) {
printf("SERVER : %s\n",bufferOut); perror("accept");
send(new_socket, bufferOut, BUFFER_SIZE, 0); exit(EXIT_FAILURE);
}
printf("Client connected\n");
while (true) {
memset(bufferIn, 0, BUFFER_SIZE);
memset(bufferOut, 0, BUFFER_SIZE);
recv(new_socket, bufferIn, BUFFER_SIZE, 0);
if(strcmp(bufferIn,"exit") == 0){
break;
}
handleClientRequest(bufferIn, bufferOut);
printf("CLIENT : %s\n", bufferIn);
printf("SERVER : %s\n", bufferOut);
send(new_socket, bufferOut, BUFFER_SIZE, 0);
}
printf("Client disconnected\n\n");
close(new_socket);
} }
close(server_fd);
} }
void handleClientRequest(char *bufferIn, char *bufferOut) { void handleClientRequest(char *bufferIn, char *bufferOut) {
...@@ -68,13 +78,13 @@ void handleClientRequest(char *bufferIn, char *bufferOut) { ...@@ -68,13 +78,13 @@ void handleClientRequest(char *bufferIn, char *bufferOut) {
break; break;
case '2': case '2':
handleClientRequestSort(bufferIn, bufferOut); handleClientRequestSort(bufferIn, bufferOut);
break; break;
} }
} }
void handleClientRequestSize(char *bufferIn, char *bufferOut) { void handleClientRequestSize(char *bufferIn, char *bufferOut) {
int len = strlen(bufferIn)-2; int len = strlen(bufferIn) - 2;
sprintf(bufferOut, "%d", len); sprintf(bufferOut, "%d", len);
} }
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment