Question

For example, I don't how many clients will connect, but I'd like for any number of clients to be able to connect during a time period, say 10 seconds.

Right now I have something like this:

unsigned int currentTime = (unsigned int)time(NULL);
int session[100], sessionCount = 0;

// accept connections for 10 seconds:
while ( (unsigned int)time(NULL) - currentTime < 10 ) {
   session[sessionCount++] = accept( my_sock_desc, (struct sockaddr *)&client_sock_addr, &sock_size );
}

This will accept any number of connections, but obviously, the last iteration of the while loop will leave a call to accept() blocking the program from continuing.

How would I solve this problem?

Was it helpful?

Solution 2

check server code here

pseudo code:

listener thread:
       while(1)
        {
        :
        : 
        if(select(...)>0)
        {
        if(FD_SET(..)) 
                  if(accept(...)) dispatch_msg_to_processing_thread;
        }
        :
        :
        }

processing thread: process message.

OTHER TIPS

You want to use select or poll with a timeout value to detect if it is safe to call accept without it blocking.

void mainloop()
{
    time_t startTime = time(NULL);
    time_t listenTime = 10; // 10 seconds, for example
    time_t elapsed = 0;

    elapsed = time(NULL) - startTime;
    secondsToWait = (elapsed >= listenTime) ? 0 : (listenTime-elapsed);
    while (secondsToWait > 0)
    {
        fd_set readset = {};
        FD_SET(my_sock_desc, &readset);
        timeval waittime = {};
        waittime.tv_sec = secondsToWait;
        int count = select(my_sock_desc+1, &readset, NULL, NULL, &waittime);
        if (FD_ISSET(my_sock_desc, &readset))
        {
            accept( my_sock_desc, (struct sockaddr *)&client_sock_addr, &sock_size );
        }

        elapsed = time(NULL) - startTime;
        secondsToWait = (elapsed >= listenTime) ? 0 : (listenTime-elapsed);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top