Napisałem prosta aplikację w C - serwer uzywając pthread.
Problem w tym, że po czasie przestaje odpowiadać - prawdopodobnie za dużo prób połączeń.
Kod:
#include<stdio.h>
#include<string.h> //strlen
#include<stdlib.h> //strlen
#include<sys/socket.h>
#include<arpa/inet.h> //inet_addr
#include<unistd.h> //write
#include<pthread.h> //for threading , link with lpthread
#include <stdint.h>
#define SERVER_PORT 8888
//the thread function
void *connection_handler(void *);
void *listen_handler();
int main(int argc , char *argv[])
{
puts("Creating server...");
pthread_t sniffer_thread;
if( pthread_create( &sniffer_thread, NULL, listen_handler ,NULL) )
{
perror("Could not create thread for listen");
return 1;
}
while(1)
{
// my code ...
delay( 1000 );
}
return 0;
}
void *listen_handler()
{
int socket_desc , client_sock , c , *new_sock;
struct sockaddr_in server , client;
//Create socket
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
printf("Could not create socket");
}
puts("Socket created");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( SERVER_PORT );
//Bind
if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
{
//print the error message
perror("bind failed. Error");
exit( 1 );
}
puts("bind done");
//Listen
listen(socket_desc , 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
while( (client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)) )
{
#ifdef DEBUG
puts("Client connected!");
#endif
pthread_t sniffer_thread;
new_sock = malloc(1);
*new_sock = client_sock;
if( pthread_create( &sniffer_thread , NULL , connection_handler , (void*) new_sock) < 0)
{
perror("Could not create thread for client");
exit( 1 );
}
//Now join the thread , so that we dont terminate before the thread
pthread_join( sniffer_thread , NULL);
//puts("Handler assigned");
}
if (client_sock < 0)
{
perror("Accept failed");
exit( 1 );
}
}
/*
* This will handle connection for each client
* */
void *connection_handler(void *socket_desc)
{
//Get the socket descriptor
int sock = *(int*)socket_desc;
int read_size;
char message[1024];
//Send reply to the client
sprintf(message, "good data!");
write(sock , message , strlen(message));
if(read_size == 0)
{
#ifdef DEBUG
puts("Client disconnected");
#endif
fflush(stdout);
}
else if(read_size == -1)
{
perror("recv failed");
}
//Free the socket pointer
free(socket_desc);
return 0;
}
Zadanie jest proste - jest połączenie serwer wysyła dane i klient się rozłącza - od razu.
Problem w tym, że jak wyłączę wszystkie klienty, to serwer dalej rejestruje połączenia.
Jakiś pomysł? Da się oczyścić jakoś kolejkę np. ustawić maksymalny czas oczekiwania przez próbę połączenia?
alagner