/******************************************************** * server2 * general without select ********************************************************/ void server2() { int masterSocket, connectedMasterSocket, numberOfFiles, *filesSocketsArr, *freePortsArr, * connectedFilesSocketsArr; struct file* files; //(1)listen on control master_socket masterSocket = listenOnPort(CONTROL_PORT); while(1){ //(2)accept new connection form master_socket puts("\n------------(1)wait for connection--------------"); connectedMasterSocket = acceptConnection(masterSocket); //(3)get port Number from client puts("\n------------(2)get number of files--------------"); numberOfFiles = getIntFromClient(connectedMasterSocket,"numberOfFiles"); //(4)listen to socket on random free ports puts("\n------------(3)listen on random ports--------------"); filesSocketsArr = listenOnSocketWithFreePorts(numberOfFiles); //(5)get filesSockets port puts("\n------------(4)random ports--------------"); freePortsArr = getPortNumberFromSockets(filesSocketsArr, numberOfFiles); //(6)send to client the free ports puts("\n------------(5)send free ports to client--------------"); SendIntArrayToClient(connectedMasterSocket,freePortsArr, numberOfFiles ,"freePortsArr"); //(7)accept connection from each of the socket in filesSocketsArr puts("\n------------(6)accept connection from new sockets--------------"); connectedFilesSocketsArr = accept_connection_from_array_of_sockets(filesSocketsArr, numberOfFiles, "filesSocketsArr"); //(8)get file from each of the socket in connectedFilesSocketsArr puts("\n------------(7)get files--------------"); files = get_files_from_array_of_sockets(connectedFilesSocketsArr, numberOfFiles); //(8)get file from each of the socket in connectedFilesSocketsArr puts("\n------------(8)save files--------------"); writeFiles(files, numberOfFiles); //(9)close master_socket, client_socket and all the socket in filesSockets puts("\n------------(9)close sockets--------------"); closeSocket(connectedMasterSocket); closeSockets(filesSocketsArr, numberOfFiles, "filesSocketsArr"); closeSockets(connectedFilesSocketsArr, numberOfFiles, "connectedFilesSocketsArr"); //(10)free filesSocketsArr and freePortsArr puts("\n------------(10)free memory--------------"); myFree(connectedFilesSocketsArr,"connectedFilesSocketsArr"); myFree(filesSocketsArr,"filesSocketsArr"); myFree(freePortsArr,"freePortsArr"); freeFiles(files, numberOfFiles,"files"); } closeSocket(masterSocket); puts("server close"); }
/* * === FUNCTION ====================================================================== * Name: idleCallback * Description: This callback gets called repeatedly. Check for new inputs and update * the graphics, and listen to the other socket * ===================================================================================== */ void idleCallback ( ) { pthread_t pth; Player p; if ( !g_sockets_init ) { g_sockets_init = 1; pthread_create( &pth, NULL, initSockets, NULL ); } if ( g_game_started ) { if ( g_curr_turn == g_num_turns ) { /* Game Ended! */ closeSockets( ); g_game_started = 0; } else if ( !g_waiting ) { /* Next Player */ g_waiting = 1; pthread_mutex_lock(&g_mutex); p = g_players[g_curr_player]; printf("Listening to player %d port...\n", g_curr_player); pthread_create( &pth, NULL, listenToSocket, NULL ); pthread_mutex_unlock(&g_mutex); } } }
/******************************************************** * freeClient * do (1) arrange the clientList * (2) free the freeNode variable ********************************************************/ void freeClient(struct clientNode* freeNode,struct clientNode** clientsList) { struct clientNode* currentNode; puts("**free client:"); //start from the head of the list currentNode = *clientsList; // free node is the first node in the list if(*clientsList == freeNode) { *clientsList = (*clientsList)->next; // free node is not the first node in the list }else { //for each client in clientlist while(currentNode->next!=NULL) { if(currentNode->next== freeNode) { currentNode->next = currentNode->next->next; break; } } } // free freeNode closeSockets(freeNode->filesSd, freeNode->countFiles,"filesSd"); myFree(freeNode->filesSd,"filesSd"); myFree(freeNode,"clientFree"); }
/*---------------------------------------------------------------------------------------------- -- FUNCTION: ~SendProcess -- -- DATE: February 27, 2015 -- -- REVISIONS: (Date and Description) -- -- DESIGNER: Calvin Rempel -- -- PROGRAMMER: Calvin Rempel, Jeff Bayntun, Manuel Gonzales -- -- INTERFACE: ~SendProcess() -- -- -- NOTES: Destructor for SendProcess. Closes sockets and kills child Process -----------------------------------------------------------------------------------------------*/ Networking::SendProcess::~SendProcess() { if (pid == 0) { closeSockets(false); // Exit the Child Process exit(0); } else if (pid > 0) { kill(pid, SIGKILL); // Wait for Child to Die int status = 0; waitpid(pid, &status, 0); closeSockets(true); } }
// Handler for cleanly closing server void closeServer() { printf("\rServer will shut down in approximately 10 seconds\n"); char message[] = "/server_closing"; emitMessageAll(message, strlen(message), clients); sleep(10); closeSockets(clients); close(srv_sock); exit(0); }
/* * === FUNCTION ====================================================================== * Name: myKeyboardFunc * Description: * ===================================================================================== */ void myKeyboardFunc( unsigned char key, int x, int y ) { switch ( key ) { case ' ': /* Space Bar */ break; case 13: /* Enter */ startGame( ); break; case 27: /* Escape key */ closeSockets(); exit(1); } }
/*---------------------------------------------------------------------------------------------- -- FUNCTION: awaitFurtherInstructions -- -- DATE: February 27, 2015 -- -- REVISIONS: (Date and Description) -- -- DESIGNER: Calvin Rempel -- -- PROGRAMMER: Calvin Rempel, Jeff Bayntun -- -- INTERFACE: void awaitFurtherInstructions() -- -- -- NOTES: child Process waits for instructions from message queue, then takes action based on message type -----------------------------------------------------------------------------------------------*/ void Networking::SendProcess::awaitFurtherInstructions() { SendMessage message; size_t result; int length = sizeof(SendMessage); int parent_value; while (1) { // < -- READ FROM MESSAGE QUEUE HERE -- > memset(&message, 0, sizeof(SendMessage)); if( (result = msgrcv(qid, &message, length, 0, 0)) == -1) { perror("error receiving message"); break; } switch(message.type) { case ADD_SOCKET: // todo: get real socket in parent value parent_value = 99; // parent_value = ??? sockets.insert({parent_value, message.socket}); break; case REMOVE_SOCKET: sockets.erase(message.socket); break; case SEND_MESSAGE: //write message to network over properly mapped socket sendNetworkMessage(message.socket, message.data); break; case SHUTDOWN: closeSockets(false); return; default: break; } } }
void Board_start() { int experimentEndTime; int updateFlag; int quitFlag; Board b; BoardThreadParams threadParams[MAX_N_ROBOTS]; BoardDatabase *db; #ifdef IS_WIN CvSize szGlobal = {ENVIR_DIMS, ENVIR_DIMS}; CvSize szLocal = {LOC_MAP_DIMS, LOC_MAP_DIMS}; IplImage *globMapIplImage; IplImage *localMapIplImage; #endif setupExperimentDir(); // Do this before setting up the database SET_N_ROBOTS(1) #ifdef SETUP_TEST_COALITION SET_N_ROBOTS(2) SET_N_ROBOTS_THREADS_FOR_TEST_COAL(1) #endif #ifdef IS_WIN globMapIplImage = cvCreateImage (szGlobal, 8, 1); localMapIplImage = cvCreateImage (szLocal, 8, 1); b = initBoard (globMapIplImage, localMapIplImage); #else b = initBoard(); #endif db = &b.db; #ifdef SETUP_TEST_COALITION Board_setupTestCoalRobots (&b.db); #endif #ifdef SHOW_IMGS Visualisation_showSim (db); Visualisation_showMap (db); // printf ("Adjust windows and click to start\n"); cvWaitKey (0); #endif if (-1 == setupSockets (db, threadParams)) { goto cleanupBoard; } experimentEndTime = clock() + 10000; printf ("Experiment ends at %d.\n", experimentEndTime); if (-1 == setupThreads (db, threadParams)) { goto cleanupBoard; } printf ("All threads started. Entering blackboard server loop.\n"); quitFlag = 0; while (!quitFlag) { enterBoardData(); checkTime (db, experimentEndTime, &updateFlag); if (updateFlag) { Board_processData (&b, 1); //! \todo Allocate coalitions quitFlag = checkIfAllFinished (db); } leaveBoardData(); if (!updateFlag) { SLEEP_FOR_MS(10) } } printf ("Finished loop. Closing sockets.\n"); closeSockets (db); Board_finish (&b); cleanupBoard: clearBoard (&b); #ifdef IS_WIN cvReleaseImage (&globMapIplImage); cvReleaseImage (&localMapIplImage); cvCleanup(); #endif }
GenericMediaServer::ClientConnection::~ClientConnection() { // Remove ourself from the server's 'client connections' hash table before we go: fOurServer.fClientConnections->Remove((char const*)this); closeSockets(); }
int main(int argc, char *argv[]) { int opt, cpid; struct sigaction sigact; while ((opt = getopt(argc, argv, "c:d:ps:nu:v")) != -1) { switch (opt) { case 'c': strcpy(confFile, optarg); break; case 'd': Debug = atoi(optarg); break; case 'p': Permiscuous = 1; break; case 'n': NoDetach = 1; break; case 'u': strcpy(PrivilegedUser, optarg); break; case 'v': Verbose = 1; break; case 's': strcpy(ControlPort, optarg); break; break; } } /* ** If they didn't ask us not to, detach from the controlling terminal ** and chdir to /etc. */ if (NoDetach == 0) { openlog("termnetd", LOG_PID | LOG_CONS, LOG_DAEMON); if ((cpid = fork()) > 0) exit(0); else if (cpid < 0) { syslog(LOG_ERR, "Quiting!! Error Detaching from terminal:%m"); exit(1); } else { chdir("/etc"); close(0); close(1); close(2); } } else openlog("termnetd", LOG_PID | LOG_CONS | LOG_PERROR, LOG_DAEMON); if (loadConfig(confFile) < 0) { syslog(LOG_ERR, "Quiting!! Error opening config file %s:%m", confFile); exit(1); } memset(&sigact, 0, sizeof(sigact)); sigact.sa_flags = SA_RESTART; sigact.sa_handler = reloadConfig; sigaction(SIGHUP, &sigact, NULL); sigact.sa_handler = retryConnections; sigaction(SIGALRM, &sigact, NULL); sigact.sa_handler = SIG_IGN; sigaction(SIGCHLD, &sigact, NULL); sigact.sa_handler = ignoreSignal; sigaction(SIGHUP, &sigact, NULL); for (;;) { Retry = 0; if (dbg) syslog(LOG_DEBUG, "main():Opening Sockets!"); openSockets(Retry); if (dbg) syslog(LOG_DEBUG, "main():Calling Socket Select!"); socketSelect(); if (Retry == 0) { if (dbg) syslog(LOG_DEBUG, "main():Closing Sockets!"); closeSockets(); } if (dbg) syslog(LOG_DEBUG, "main():Loading Config file!"); if (loadConfig(confFile) < 0) { syslog(LOG_ERR, "Quiting!! Error opening config file %s:%m", confFile); exit(1); } if (dbg) syslog(LOG_DEBUG, "main():Grabbing 60 winks!"); } #ifndef SCO exit(0); #endif }
int main(int argc, char const *argv[]) { //inicializacao if(initializeCommunication(argc, argv) != 0) exit(-1); //inicailizacao falhou putdebug("inicialização completa\n"); //inicializar conjunto de ligacoes initializeConnectionSet(); int maxFd = curNode.fd; //descritor com valor mais elevado char buffer[BUFSIZE]; //buffer utilizado para fazer a leitura dos descritores int inputReady = 0; //indica se existe input disponivel para ler int quit = FALSE; while(!quit) { //reinicializar conjunto de fds de leitura FD_ZERO(&readFds); //adicionar ligacoes no conjunto de fds copySet(&readFds); //adicionar listen fd ao conjunto de fds FD_SET(curNode.fd, &readFds); //adicionar stdin ao conjunto de fds FD_SET(STDIN_FILENO, &readFds); putdebug("CurNode - ring: %d id: %d ip: %s port: %s fd: %d", curRing, curNode.id, curNode.ip, curNode.port, curNode.fd); putdebug("SucciNode - id: %d ip: %s port: %s fd: %d", succiNode.id, succiNode.ip, succiNode.port, succiNode.fd); putdebug("PrediNode - id: %d ip: %s port: %s fd: %d", prediNode.id, prediNode.ip, prediNode.port, prediNode.fd); if(maxFd < getMaxConnection()) { maxFd = getMaxConnection(); } //esperar por descritor pronto para ler putmessage("\r> "); inputReady = select(maxFd + 1, &readFds, NULL, NULL, NULL); if(inputReady <= 0) { putdebugError("main", "select falhou"); continue; } if(FD_ISSET(curNode.fd, &readFds)) { //testar se o listen fd esta pronto para leitura struct sockaddr_in addr; socklen_t addrlen = sizeof(addr); bzero(&addr, addrlen); //aceitar ligacao int connectionFd; if( (connectionFd = accept(curNode.fd, (struct sockaddr*)&addr, &addrlen)) == -1) { putdebugError("main", "ligação não foi aceite"); } else { putdebug("nova ligação %d com endereço: %s", connectionFd, inet_ntoa(addr.sin_addr)); //adicionar descritor ao conjunto de descritores de ligacao addConnection(connectionFd); //definir um timeout para as comunicações struct timeval tv; tv.tv_sec = 5; setsockopt(connectionFd, SOL_SOCKET, SO_SNDTIMEO,(struct timeval *)&tv,sizeof(struct timeval)); setsockopt(connectionFd, SOL_SOCKET, SO_RCVTIMEO,(struct timeval *)&tv,sizeof(struct timeval)); } } if(FD_ISSET(STDIN_FILENO, &readFds)) { //testar se o utilizador executou um comando //ler comando do utilizador bzero(buffer, sizeof(buffer)); if(fgets(buffer, BUFSIZE, stdin) != NULL) { //executar comando do utilizador putdebug("processar comando do utilizador"); int errorCode = executeUserCommand(buffer); switch(errorCode) { case 0: putdebug("comando de utilizador processado com sucesso"); break; case -1: putdebugError("main", "falha no processamento do comando de utilizador"); break; case 1: { putmessage("programa vai sair\n"); //fechar todos os sockets int fd = getFirstConnection(); while(fd >= 0) { close(fd); rmConnection(fd); //proxima ligacao fd = getNextConnection(fd); } //fechar socket de escuta e socket do servidor de arranque closeSockets(); quit = TRUE; continue; } } } } //ler fds de ligacoes actuais com o nó int connectionFd = getFirstConnection(); while(connectionFd >= 0) { if(FD_ISSET(connectionFd, &readFds)) { //limpar buffer de rececao bzero(buffer, sizeof(buffer)); //ler mensagem if(readMessage(connectionFd, buffer, sizeof(buffer)) <= 0) { close(connectionFd); //fechar ligacao rmConnection(connectionFd); //remover no do conjunto de ligacoes putdebug("ligacao %d terminada", connectionFd); if(connectionFd == prediNode.fd) { prediNode.fd = -1; prediNode.id = -1; putdebug("ligação terminada com predi"); if(succiNode.fd == -1 && !iAmStartNode) { //estou sozinha mas não sou o nó de arranque //isto significa que houve uma saida abrupta //registar num novo anel if(registerNewRing() == -1) { putdebugError("handleEND", "não foi possível registar novo anel"); return -1; } } } if(connectionFd == succiNode.fd) { succiNode.fd = -1; succiNode.id = -1; putdebug("ligação terminada com succi"); //colocar um alarme de 2 segundos para garnatir que todas as ligações //que são par ser terminadas têm efeito no estado do nó signal(SIGALRM, rebuildSignal); alarm(REBUILD_INTERVAL); } } else { //tratar mensagem recebida putdebug("mensagem recebida pela ligacao %d: %s", connectionFd, buffer); //remover \n int length = strlen(buffer); if(buffer[length - 1] == '\n') buffer[length - 1] = '\0'; if(strcmp(buffer, "ERROR") == 0) { //houve um erro na comunicação TCP puterror("ocorreu um erro na comunicação entre nós\n"); closeConnection(&connectionFd); continue; } if(handleMessage(buffer, connectionFd) == -1) { //notificar quem enviou o pedido que ocorreu um erro char answer[] = "ERROR\n"; sendMessage(connectionFd, answer); if(connectionFd == prediNode.fd) { prediNode.fd = -1; prediNode.id = -1; putdebug("ligação terminada com predi por causa de erro"); } if(connectionFd == succiNode.fd) { succiNode.fd = -1; succiNode.id = -1; putdebug("ligação terminada com succi por causa de erro"); } //terminar ligacao closeConnection(&connectionFd); } } } //proxima ligacao connectionFd = getNextConnection(connectionFd); } } return 0; }