Advertisement
adibdoub

Untitled

Oct 13th, 2015
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.85 KB | None | 0 0
  1. void * fctThread (void *param);
  2. pthread_mutex_t mutexThread;
  3. pthread_cond_t clientCond;
  4. int actualClient = -1;
  5. Socket *clientSockets[MAXCLIENT];
  6. ServerSocket *serverSocket;
  7.  
  8. #define LOCK(mutex) pthread_mutex_lock(mutex)
  9. #define UNLOCK(mutex) pthread_mutex_unlock(mutex)
  10. #define COND_WAIT(condition, mutex) pthread_cond_wait(condition, mutex)
  11. #define COND_SIGNAL(condition) pthread_cond_signal(condition)
  12.  
  13. int main(int argc, const char * argv[]) {
  14.    
  15.     pthread_t threadHandles[MAXCLIENT];
  16.     int i;
  17.     pthread_mutex_init(&mutexThread, NULL);
  18.     pthread_cond_init(&clientCond, NULL);
  19.    
  20.     createFICHPARCRecords(fileName);
  21.     displayFICHPARC(fileName);
  22.    
  23.     /*Initializing all client sockets and client threads*/
  24.     for (i=0; i<MAXCLIENT; i++) {
  25.         clientSockets[i] = NULL;
  26.         pthread_create(&threadHandles[i], NULL, fctThread, NULL);
  27.     }
  28.    
  29.     //Starting the server
  30.     try {
  31.         serverSocket = new ServerSocket("50001");
  32.     } catch (SocketException& exc) {
  33.         cout<<exc.getExplanation()<<endl;
  34.         exit(1);
  35.     }
  36.  
  37.     while (true)
  38.      {
  39.         //Looking for a free socket slot
  40.          for (i=0; i<MAXCLIENT && clientSockets[i] != NULL; i++);
  41.          if (i == MAXCLIENT) {
  42.              //No places anymore
  43.          }
  44.          else
  45.          {
  46.             //free socket slot found on i
  47.             try {
  48.                 clientSockets[i] = serverSocket->acceptClient();
  49.                 cout<<"A client connected"<<endl;
  50.                 LOCK(&mutexThread);
  51.                 actualClient = i;
  52.                 COND_SIGNAL(&clientCond);
  53.                 UNLOCK(&mutexThread);
  54.             } catch (SocketException &Exc) {
  55.                 //Someone tried to connect but failed, we should accept a new client on the same socket slot (so i--)
  56.                 cout<<Exc.getExplanation()<<endl;
  57.                 i--;
  58.             }
  59.          }
  60.     }
  61.     return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement