stop crashing server when client disconnects

This commit is contained in:
socec 2014-03-09 18:48:04 +01:00
parent 98333194db
commit 199d2cb6c2
3 changed files with 19 additions and 2 deletions

View file

@ -1,7 +1,7 @@
#include "moxerver.h"
#define SERVER_WAIT_TIMEOUT 10 /* seconds for select() timeout in server loop */
#define SERVER_WAIT_TIMEOUT 5 /* seconds for select() timeout in server loop */
#define PORT_MIN 4001 /* minimum TCP port number */
#define PORT_MAX 4008 /* maximum TCP port number */
@ -137,7 +137,18 @@ int main(int argc, char *argv[]) {
}
}
if (ret == 0) {
fprintf(stderr, "server waiting\n");
/* check if client disconnected */
/* a disconnected client socket is ready for reading but read returns 0 */
if ( (client.socket != -1) && FD_ISSET(client.socket, &read_fds) ) {
if (client_read(&client) == 0) {
fprintf(stderr, "client %s disconnected\n", client.ip_string);
/* close client connection */
client_close(&client);
}
}
else {
fprintf(stderr, "server waiting\n");
}
}
} /* END while loop */

View file

@ -1,6 +1,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>

View file

@ -85,6 +85,11 @@ int server_accept(struct server_t *server, struct client_t *accepted_client) {
fprintf(stderr, "[%s:%d] error %d: %s\n", __func__, __LINE__, errno, strerror(errno));
return -errno;
}
/* make client socket non-blocking */
if (fcntl(accepted_client->socket, F_SETFL, O_NONBLOCK) == -1) {
fprintf(stderr, "[%s:%d] error %d: %s\n", __func__, __LINE__, errno, strerror(errno));
return -errno;
}
/* get client IP address as human readable string */
inet_ntop(accepted_client->address.sin_family, &accepted_client->address.sin_addr.s_addr,