void *commandReadThreadFunc(void *arg) { int i; fd_set readset, exceptset; int highest; int numclients; dbg_clear(DBG_SIM, "SIM: commandReadThread running.\n"); while (1) { // Build up the fd_set FD_ZERO(&readset); FD_ZERO(&exceptset); FD_SET(commandServerSocket, &readset); FD_SET(commandServerSocket, &exceptset); highest = commandServerSocket; numclients = 0; for (i = 0; i < MAX_CLIENT_CONNECTIONS; i++) { if (commandClients[i] != -1) { if (commandClients[i] > highest) highest = commandClients[i]; EC_DEBUG(fprintf(stderr, "SIM: commandReadThread: Adding fd %d to select set\n", commandClients[i])); FD_SET(commandClients[i], &readset); FD_SET(commandClients[i], &exceptset); numclients++; } } EC_DEBUG(fprintf(stderr, "SIM: commandReadThread: Doing select, %d clients, highest %d\n", numclients, highest)); if (select(highest+1, &readset, NULL, &exceptset, 0) < 0) { dbg_clear(DBG_SIM, "SIM: commandReadThreadFunc: error in select(): %s\n", strerror(errno)); } EC_DEBUG(fprintf(stderr, "SIM: commandReadThread: Returned from select\n")); // Read from clients and check for errors for (i = 0; i < MAX_CLIENT_CONNECTIONS; i++) { /*EC_DEBUG(fprintf(stderr, "SIM: commandClients[i] %d excepta %d read %d\n", commandClients[i], ((commandClients[i] != -1)? FD_ISSET(commandClients[i], &exceptset) : -1), ((commandClients[i] != -1)? FD_ISSET(commandClients[i], &readset) : -1)));*/ if (commandClients[i] != -1 && FD_ISSET(commandClients[i], &readset)) { if (readTossimCommand(commandClients[i], i) < 0) { close(commandClients[i]); commandClients[i] = -1; } } if (commandClients[i] != -1 && FD_ISSET(commandClients[i], &exceptset)) { // Assume we need to close this one close(commandClients[i]); commandClients[i] = -1; } } // Check for new clients if (FD_ISSET(commandServerSocket, &readset)) { int clifd; EC_DEBUG(fprintf(stderr, "SIM: commandReadThread: accepting command connection\n")); clifd = acceptConnection(commandServerSocket); EC_DEBUG(fprintf(stderr, "SIM: commandReadThread: Got command connection %d\n", clifd)); addClient(commandClients, clifd); } } return 0; }
/* Main server routine */ void startServer(int port){ int socketDescriptor = setupSocket(port); if(socketDescriptor==-1) /* Return on failure, flag already set. */ return; /* Set timeout values */ struct timeval timeOut; timeOut.tv_sec = 0; timeOut.tv_usec = 0; fd_set master; /* Master socket descriptor set */ fd_set read_sds; /* Temporary socket descriptor set */ FD_ZERO(&master); FD_ZERO(&read_sds); int maxsd; /* Maximum descriptor number */ char buffer[MAX_BUFFER]; /* For incoming data storage */ /* Add current socket to master set */ FD_SET(socketDescriptor, &master); addToConnectionTable("broadcast",-1); /* Broadcast dummy user, to broadcast message */ maxsd = socketDescriptor; SERVER_SOCKET = socketDescriptor; std::cout<<"Server is ready for operations...\n"; /* Main server loop */ while(true){ memcpy(&read_sds, &master, sizeof(fd_set)); /* Make a temporary copy */ /* NULL for writefd and exceptfd (Not needed) */ int s = select(maxsd+1, &read_sds, NULL, NULL, &timeOut); if(s<0){ ERROR = E_SELECT; error_message = "Error using select."; #ifdef __DEBUG__ std::cout<<error_message<<std::endl; #endif continue; } /* Search for data to read */ for(int sock=0;sock<=maxsd;++sock){ if(FD_ISSET(sock, &read_sds)){ /* Pending read status found */ if(sock == socketDescriptor){ /* If match on socket descriptor of server */ int newSd = acceptConnection(socketDescriptor); if(newSd>-1){ FD_SET(newSd, &master); maxsd = std::max(maxsd, newSd); /* Update maximum descriptor */ } } else{ /* Handle data from client */ int nbytes = receiveData(sock, buffer); if(nbytes==-1){ removeFromConnectionTable(sock); close(sock); FD_CLR(sock, &master); /* Update the master socket descriptor set */ }else{ processRequest(sock, buffer); } } } } } }
void TreeWalker::acceptConnections(DomConnections *connections) { for (int i=0; i<connections->elementConnection().size(); ++i) acceptConnection(connections->elementConnection().at(i)); }
/// @brief mainwindow constructor MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); // Load settings /// @todo, replace for ini file or qsettings. defaultUserSettings(); // Create secondary windows about = new About(); config = new Config(); // Connect close event, this inclused save connect(config,SIGNAL(closed(Config::ConfigExitCode)),this,SLOT(config_closed(Config::ConfigExitCode))); // Initialise the line assembler lineAssembler = new LineAssembler(); // Create viewmanager views = new ViewManager(16); connect(views,SIGNAL(viewVisibilityChanged(QString)),this,SLOT(on_viewVisibilityChanged(QString))); // Create the filtermanager filters = new FilterManager(); // Initialize listFilter system checkboxes = new QList<Qt::CheckState>; checkboxes->append(Qt::Checked); ui->listFilter->addItem(QString("*")); ui->listFilter->item(0)->setCheckState(Qt::Checked); // Create a driverManager driverManager = new DriverManager(&user_settings); // Connect driver state changed connect(driverManager,SIGNAL(stateChanged(DriverManager::DriverState)), this,SLOT(driver_stateChanged(DriverManager::DriverState))); // Platform specific init #ifdef Q_OS_WIN //#elif Q_OS_LINUX /// @todo implement linux of tty->tcp //#elif Q_OS_MAC /// @todo implement mac of tty->tcp #else QMessageBox msgBox; msgBox.setText("There is no com/tty driver support for your platform,\nplease connect to the tcp server manually "); msgBox.exec(); #endif // Start the TCP server tcpServer = new QTcpServer(); connect(tcpServer, SIGNAL(newConnection()), this, SLOT(acceptConnection())); while(!tcpServer->listen(QHostAddress::LocalHost,user_settings.server.portnumber)){ user_settings.server.portnumber++; } tcpServerConnectionValid = false; tcpServerStatus.setText("Server: Initializing"); // Initialize the statusbar statusbartext.setText("<img src=':/icons/resources/icons/cross.png' /> Driver: Stopped"); ui->statusBar->addWidget(&statusbartext,1); ui->statusBar->addWidget(&tcpServerStatus,1); // Spawn some timers for refreshing gui viewUpdater = new QTimer(); connect(viewUpdater, SIGNAL(timeout()), this, SLOT(updateViews())); viewUpdater->setInterval(10); viewUpdater->start(); mainWindowUpdater = new QTimer(); connect(mainWindowUpdater,SIGNAL(timeout()),this,SLOT(updateMainWindow())); mainWindowUpdater->setInterval(100); mainWindowUpdater->start(); }
LocalServer::LocalServer(QObject *parent) : QTcpServer(parent) { connect(this, SIGNAL(newConnection()), SLOT(acceptConnection())); }
void* loginThreadHandler (void* port) { int loginPort = (*((int*)port)); pthread_t clientthread [MAX_PLAYERS]; struct sockaddr_in serverAddr; int listensocket , tcpsocket; tcpsocket = socket(AF_INET,SOCK_STREAM,0); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(loginPort); serverAddr.sin_addr.s_addr = INADDR_ANY; //Bind if( bind(tcpsocket,(struct sockaddr *)&serverAddr , sizeof(struct serverAddr)) < 0) { //print the error message perror("[server]bind failed. error\n"); close(tcpsocket); return 1; } puts("[server]bind successfull"); //Listen if( listen( tcpsocket, 3 ) < 0 ) { errorPrint("[server]listen error "); close(tcpsocket); return -1; } puts("[server]listening ,waiting for incoming connections...\n"); listensocket = accept(loginPort,NULL ,NULL); printf ("[login] listensocket: %d \n",listensocket); if (listensocket == -1) { printf ("[login]listensocket shitti , try new port.\n"); exit(0); } initialisePlayers(); // Setzt alle Sockets auf -1 //Warte bis vier Spieler verbunden. Vorher hörst du den Clients zu, guckst erstens ob der Startgame definitiv vom Leiter kommt //und ob auch vier Spieler (clientCount?) eingeloggt sind! //Dann könnts los gehen. Wenn startgame nachricht an nicht leiter geht, virtuel den Startbutton bei den dreien klicken (optional) //====================================Los geht's, warten wir auf verbindungsfreudige Clienten================================== while (1) { printf ("[login] ready to connect\n"); int sendsocket = acceptConnection (listensocket); printf ("[login] Sendsocket %d \n",sendsocket); printf ("[login] Waiting for message from client \n"); MESSAGE lrqMsg; MTYPE type = 0; type = recvMSG (sendsocket, &lrqMsg); if (type == MTYPE_LRQ) { if (1) { printf("ok alles klar soweit"); } else { MESSAGE errMsg = createERR (ERR_SUBTYPE_FATAL,"***[login] Ungültige RFC Version! ( !=8)***\n"); sendMSG (sendsocket,&errMsg); close (sendsocket); } } else { MESSAGE errMsg; if (getID () == -1) { errMsg = createERR (ERR_SUBTYPE_FATAL,"***[login] Server voll!***\n"); } sendMSG (sendsocket,&errMsg); close (sendsocket); } } return NULL; }
int main ( int argc, char * argv[ ] ) { int sock, nuSock; // This will be our sockets int nbytes; // Number of bytes we receive in our message int code; // Error code for Select char buffer[ MAXBUFSIZE ]; // A buffer to store our received message char msg[ MAXBUFSIZE ]; // A Message to return Repository repo; // The registration list fd_set fds; struct timeval timeout; int count = 0; // // Make sure port is given on command line // if ( argc != 2 ) { printf( "USAGE: <port>\n" ); exit( EXIT_FAILURE ); } // // Initialize all the things! // repo.total = 0; maxPrint( &repo ); sock = createSocket( atoi( argv[1] ) ); timeout.tv_sec = 2; timeout.tv_usec = 0; FD_ZERO( &fds ); FD_SET( sock, &fds ); nuSock = acceptConnection( sock ); ERROR( nuSock < 0 ); FD_SET( nuSock, &fds ); // // Enter command loop // for ( ; ; ) { /* if ( ( code = select( sizeof( fds )*8, &fds, NULL, NULL, &timeout ) ) < 0 ) { ERROR( code < 0 ); } else if ( code == 0 ) { printf( "$ Timeout [%i]\r", count = ++count % 100 ); ERROR( count ); } else { count = 0; if ( FD_ISSET( sock, &fds ) ) { // Loop through all the conenctions Available while ( ( nuSock = acceptConnection( sock ) ) > 0 ); FD_SET( nuSock, &fds ); } */ ERROR( nuSock < 0 ); bzero( buffer, MAXBUFSIZE ); nbytes = read( nuSock, buffer, MAXBUFSIZE ); ERROR( nbytes < 0 ); printf( "[%s] %s\n", repo.cxn[whoisthis( &repo, nuSock )].name, buffer ); switch ( parseCmd ( buffer ) ) { case CONNECT: { nbytes = write( nuSock, buffer, MAXBUFSIZE ); ERROR( nbytes < 0 ); switch( registerClient( &repo, nuSock ) ) { case SUCCESS: getList ( &repo, nuSock ); printf( "> Success in registering '%s'\n", repo.cxn[repo.total-1].name ); break; case FAILURE: printf( "> Error in registration\n" ); break; } break; } case GET: sendMaster( &repo, nuSock ); break; case EXIT: { switch( removeClient( &repo, nuSock ) ) { case SUCCESS: printf( "> Client has been removed.\n" ); break; case FAILURE: printf( "> Error removing client.\n" ); break; } break; } default: sprintf( msg, "Invalid command: '%s'", buffer); nbytes = write( nuSock, msg, MAXBUFSIZE ); ERROR( nbytes < 0 ); break; } } close( nuSock ); close( sock ); return EXIT_SUCCESS; } // main( )
//-- main() ///{{{1/////////////////////////////////////////// int main( int argc, char* argv[] ) { int serverPort = kServerPort; fd_set readfds; fd_set writefds; int maxFd, activity, sd; std::vector<ConnectionData> connections; // Did the user specify a port? if( 2 == argc ) { serverPort = atoi(argv[1]); } # if VERBOSE printf( "Attempting to bind to port %d\n", serverPort ); # endif // Set up listening socket - see setup_server_socket() for details. int listenfd = setup_server_socket( serverPort ); if( -1 == listenfd ) return 1; // loop forever while( 1 ) { FD_ZERO(&readfds); // Clear the read socket set FD_ZERO(&writefds); // Clear the read socket set FD_SET(listenfd, &readfds); // Add the listen socket to the read set maxFd = listenfd; // Initially add the listen socket as the maximum file descriptor // Add the client descriptors to the set. for(size_t i = 0; i < connections.size(); i++){ sd = connections[i].sock; if(sd > 0){ if(connections[i].state == eConnStateReceiving) //Add connections to the corresponding sets FD_SET(sd, &readfds); else if(connections[i].state == eConnStateSending) FD_SET(sd, &writefds); } if(sd > maxFd){ // Change maxFd if the file descriptor of the client is larger than the current maxium maxFd = sd; } } activity = select(maxFd + 1, &readfds, &writefds, NULL, NULL); // Perform select to find pending reads and writes if((activity < 0) && (errno != EINTR)){ // Check so that no errors occured. printf("select error \n"); // Should we have "else" } if(FD_ISSET(listenfd, &readfds)){ // If there is activity on the listening socket // Accept connection and add it to the list. if(acceptConnection(&connections, listenfd) == -1) continue; continue; } // Loop through all connections and check if they members of a set for(size_t i=0; i<connections.size(); i++){ sd = connections[i].sock; //Copy the socket descriptor bool processFurther = true; if(FD_ISSET(sd, &readfds)){ while( processFurther && connections[i].state == eConnStateReceiving ) processFurther = process_client_recv( connections[i] ); } else if(FD_ISSET(sd, &writefds)){ while( processFurther && connections[i].state == eConnStateSending ) processFurther = process_client_send( connections[i] ); } if(!processFurther){ // Close the socket if processing is finished close(connections[i].sock); connections[i].sock = -1; } } //Erase all invalid connections connections.erase(std::remove_if(connections.begin(), connections.end(), &is_invalid_connection),connections.end()); } // The program will never reach this part, but for demonstration purposes, // we'll clean up the server resources here and then exit nicely. close( listenfd ); return 0; }
void TCPServer::init() { connect(&m_tcpServer, SIGNAL(newConnection()), this, SLOT(acceptConnection())); }
void OlySocket::createSingleServerConnection(int port) { createServerSocket(port); mSocketID = acceptConnection(); closeServerSocket(); }
/** * loopServer * * Boucle principale de l'entrée. * Création d'un serveur et écoute les connexions entrantes et stdin. * Si une connexion socket ou stdin est prêt à lire, appel de readFd */ void loopServer() { int port = -1; int socketServeur = -1; //le socket d'écoute de connexions if ((socketServeur = initSocket(&port)) == -1) { perror("Can't create socket"); exit(EXIT_FAILURE); } DEBUG("[server] socket serveur fd=%d on port %d", socketServeur, port); printf("Listening on port %d\n", port); printPrompt(fileno(stdin)); //Écoute fd_set socketsToRead; //la liste de socket à lire int maxSocket; //le plus grand fd parmis socketsToRead initListen(socketServeur, &socketsToRead, &maxSocket); while (42) { fd_set readyToRead; selectSocket(&socketsToRead, &readyToRead, maxSocket); //On regarde la plage où se trouvent tous nos file descriptor for (int fd = 0; fd <= maxSocket; fd++) { if (FD_ISSET(fd, &readyToRead)) { //fd est prêt à être lu //une nouvelle connection sur le serveur if (fd == socketServeur) { int sock = acceptConnection(fd, &socketsToRead, &maxSocket); printPrompt(sock); } else { //Une entrée DEBUG("[server] Reading input %d", fd); int child = fork(); DEBUG("[server] Create child to handle connection %d", fd); if (child ==0) { //dans le fils setSigHandler(SIGINT_handler_nothing, SIGINT); readInputServer(fd); DEBUG("[worker] stop, connection end %d", fd); if (fd == fileno(stdin)) { //on informe le parent qu'il doit se terminer DEBUG("tell parent to stop"); kill(getppid(), SIGUSR1); } else { dprintf(fd, "\nBye !\n"); close(fd); } exit(EXIT_SUCCESS); } else { //dans le parent //ne plus écouter ce socket FD_CLR(fd, &socketsToRead); } } } } } }
void GameSocket::newConnection(int sock) { emit acceptConnection(sock); }