int transporter_C::connect_Socket()
{
    int err;
    int bytecount = 0;
    char data[1024];


    if( connect( hsock, (struct sockaddr*)&my_addr, sizeof(my_addr)) == -1 )
    {
        if((err = errno) != EINPROGRESS)
        {
            fprintf(stderr, "Error connecting socket %d\n", errno);
            exitClient(hsock);
            return -1;
        }
    }
    buffer_len = 1024;
    memset(buffer, '\0', buffer_len);
    strcpy(buffer, configuration[0].name.c_str());

    SetupCode(data);

    if( (bytecount=send(hsock, (const void*)data, 1024,0)) < 1)
    {
        fprintf(stderr, "send_Data Error sending data %d\n", errno);
        exitClient(hsock);
        return -1;
    }

    memset(buffer, '\0', buffer_len);

    if((bytecount = recv(hsock, buffer, buffer_len, 0)) < 1)
    {
        fprintf(stderr, "Error receiving data %d\n", errno);
        exitClient(hsock);
    }

    unsigned char magic;
    unsigned int ps2;
    char s2[96];

    unpack((unsigned char*)buffer, "CHs",   &magic,
                                            &ps2,
                                            &s2);

    printf("recv: '%c' %hhu %s\n",  magic,
                                    ps2,
                                    s2);

    if(magic == 69)
    {
        cout << "se cerro"<< endl;
        exitClient(hsock);
        return -1;
    }
    return 0;
}
Esempio n. 2
0
bool Client::initLocal( const int argc, char** argv )
{
    if( _impl->name.empty() && argc > 0 && argv )
    {
        const boost::filesystem::path prog = argv[0];
        setName( prog.stem().string( ));
    }

    const auto options = _getProgramOptions();
    arg::variables_map vm;
    try
    {
        Strings args;
        for( int i = 0; i < argc; ++i )
            if( strcmp( argv[i], "--" ) != 0 )
                args.push_back( argv[i] );

        arg::store( arg::command_line_parser( args )
                        .options( options ).allow_unregistered().run(), vm );
        arg::notify( vm );
    }
    catch( const std::exception& e )
    {
        LBERROR << "Error in argument parsing: " << e.what() << std::endl;
        return false;
    }

    const bool isClient = vm.count( "eq-client" );
    std::string clientOpts;

    if( vm.count( "eq-layout" ))
        _impl->activeLayouts.push_back( vm["eq-layout"].as< std::string >( ));
    if( vm.count( "eq-gpufilter" ))
        _impl->gpuFilter = vm["eq-gpufilter"].as< std::string >();
    if( vm.count( "eq-modelunit" ))
        _impl->modelUnit = vm["eq-modelunit"].as< float >();

    LBVERB << "Launching " << getNodeID() << std::endl;
    if( !Super::initLocal( argc, argv ))
        return false;

    if( isClient )
    {
        LBVERB << "Client node started from command line with option "
               << clientOpts << std::endl;

        if( !_setupClient( clientOpts ))
        {
            exitLocal();
            return false;
        }

        _impl->running = true;
        clientLoop();
        exitClient();
    }

    _impl->initQt( argc, argv );
    return true;
}
Esempio n. 3
0
void BtsSpawnClient::restartClient()
{
	if(!p->clientProc)
	{
		startClient();
	}
	else
	{
		connect(p->clientProc.data(), SIGNAL(finished(int)), this, SLOT(startClient()));
		exitClient();
	}
}
int AaronMR_S::connect_Socket()
{
    int err;
    int bytecount = 0;
    if( connect( hsock, (struct sockaddr*)&my_addr, sizeof(my_addr)) == -1 )
    {
        if((err = errno) != EINPROGRESS)
        {
            fprintf(stderr, "Error connecting socket %d\n", errno);
            exitClient(hsock);
        }
    }

    buffer_len = 1024;
    memset(buffer, '\0', buffer_len);
    memcpy(buffer, configuration[0].name.data(), configuration[0].name.length() );
    cout << "The name of the service is = " << buffer << endl;

    if( (bytecount=send(hsock, buffer, strlen(buffer),0))== -1)
    {
        fprintf(stderr, "Error sending data %d\n", errno);

        exitClient(hsock);
    }

    memset(buffer, '\0', buffer_len);

    if((bytecount = recv(hsock, buffer, buffer_len, 0))== -1)
    {
        fprintf(stderr, "Error receiving data %d\n", errno);
        exitClient(hsock);
    }
    printf("Recieved bytes %d\nReceived string \"%s\"\n", bytecount, buffer);

    if(strcmp(buffer, "close") == 0)
    {
        cout << "se cerro"<< endl;
        exitClient(hsock);
    }
}
Esempio n. 5
0
int disconnect (int *maxfds, fd_set *readfds, int *num_clients, client_data *fd_array, char *msg) {

	char *posSpace = NULL;
	char name[MAX_SIZE_USERNAME];
	int i, bchar;
	int client_sockfd;

	if(strlen(msg) < MIN_SIZE_USERNAME+12 || strlen(msg) > MAX_SIZE_USERNAME+12) { // "/disconnect " = 12
		printf(BLUE"[PROGRAM] Error command : Username too short or too long.\n[PROGRAM] Please use \"/disconnect username\"."RESET"\n\n");
		return -1;
	}

	if((posSpace = strchr(msg, ' ')) == NULL){
    printf(BLUE"[PROGRAM] Error command. Please use \"/disconnect username\"."RESET"\n\n");
    return -1;
  }
	if(strcpy(name, posSpace+1) == NULL) {
		printf(BLUE"[PROGRAM] Error command. Please use \"/disconnect username\"."RESET"\n\n");
		return -1;
	}
	name[strlen(name) - 1] = '\0';
	for(i=0 ; i < strlen(name) ; i++) {
    bchar = (isalnum((unsigned char) name[i])) ? 0 : 1;
    if(bchar) {break;}
  }
  if (bchar) {
    printf(BLUE"[PROGRAM] Error command : Username must only be composed of alphanumeric characters.\n[PROGRAM] Please use \"/disconnect username\".\n"RESET"\n\n");
    return -1;
  }

	if((client_sockfd = search_client_fd_by_name(name, fd_array, num_clients)) < 0) {
		printf(BLUE"Client is not connected"RESET"\n\n");
		return -1;
	}
	/* Fin de l'initialisation / gestion d'erreurs : on alloue de la mémoire */
	message *discomsg = (message *) malloc(sizeof(message));
	if (fd_array[search_client_array_by_fd(client_sockfd, fd_array, num_clients)].fd_transfer != 0) {
		printf(BLUE"[PROGRAM] Transfer aborted"RESET"\n");
		transfer_aborted(discomsg);
		send_msg(discomsg, &client_sockfd, readfds, fd_array, num_clients);
		close(fd_array[search_client_array_by_fd(client_sockfd, fd_array, num_clients)].fd_transfer);
		fd_array[search_client_array_by_fd(client_sockfd, fd_array, num_clients)].fd_transfer = 0;
	}
	session_end(discomsg);
	send_msg(discomsg, &client_sockfd, readfds, fd_array, num_clients);
	exitClient(client_sockfd, readfds, fd_array, num_clients);
	free((*discomsg).msg_content);
	free(discomsg);
	return 0;

}
int transporter_C::recv_Data()
{
    char data[1024];
    int bytecount = 0;

    if( (bytecount=recv(hsock, (void*)data, 1024,0)) < 1)
    {
        fprintf(stderr, "recv_Data Error reciving data %d\n", errno);
        exitClient(hsock);
        return -1;
    }

    if(configuration[0].DEBUG)
            structToRecv->printStruct(data);

    structToRecv->Unserialize(data);
    return 0;
}
Esempio n. 7
0
void Login::loginButtonPressed() {
    QString ip = ui->lineEdit->text();
    int port = ui->lineEdit_2->text().toInt();
    QString name = ui->lineEdit_3->text();
    socket = new QTcpSocket(this);
    connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(connectionError(QAbstractSocket::SocketError)));
    socket->connectToHost(ip, port);
    if(!socket->waitForConnected(3000)) {

    }
    else {
        int csize = 0;
        Message m(1, 0, 0, 0, ui->lineEdit_3->text().toUtf8());
        m.send(socket);
        socket->waitForReadyRead(-1);
        QByteArray chunk = socket->read(4);
        memcpy(&csize, chunk, 4);
        QByteArray buffer = socket->read(csize);
        Message message;
        message.createMessage(buffer, csize);
        int userID = message.getDest();
        if(strcmp(message.getBuffer(), "OK") == 0) {
            main =  new MainWindow(ip, port, name, socket, userID);
            connect(main, SIGNAL(exit()), this, SLOT(exitClient()));
            this->hide();
            disconnect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(connectionError(QAbstractSocket::SocketError)));
            main->show();
        }
        else {
            QMessageBox::StandardButton resBtn = QMessageBox::question( this, "ChatClient",
                                                                        "This username is already used by another user!",
                                                                        QMessageBox::Retry | QMessageBox::Close);
            if (resBtn == QMessageBox::Cancel) {
                socket->close();
                this->close();
            }
            else {
                socket->close();
                delete socket;
            }
        }
    }
    //this->show();
}
int transporter_C::send_Data()
{
    char data[1024];
    int bytecount = 0;

    structToSend->spinOnce();

    if(structToSend->canSend())
    {
        structToSend->serialize(data);
        if(configuration[0].DEBUG)
            structToSend->printStruct(data);

        if( (bytecount=send(hsock, (const void*)data, 1024,0)) < 1)
        {
            fprintf(stderr, "send_Data Error sending data %d\n", errno);
            exitClient(hsock);
            return -1;
        }
    }
    return 0;
};
int AaronMR_S::acceptConnection()
{


        int csock;
		printf("waiting for a connection\n");
		//csock = (int*)malloc(sizeof(int));



		/*
		// funcion para activar y desactivar el envio de datos....
		while(1)
        {
            pthread_mutex_lock(&configuration[process2Active].mutex);

            configuration[process2Active].canRecv = rand() % 2 + -1;
            configuration[process2Active].canSend = rand() % 2 + -1;

            pthread_mutex_unlock(&configuration[process2Active].mutex);

            usleep(1000);

        }
        */



		if((csock = accept( hsock, (sockaddr*)&sadr, &addr_size))!= -1){
			printf("---------------------\nReceived connection from %s\n",inet_ntoa(sadr.sin_addr));

			cout << "---------------------------" << endl;

            char buffer[1024];

            int buffer_len = 1024;
            int bytecount;
            memset(buffer, 0, buffer_len);
            DataLayout processThread;

            //if((bytecount = recv(csock, buffer, buffer_len, 0))== -1){
            //    fprintf(stderr, "Error receiving data %d\n", errno);
            //    //goto FINISH;
            //}

            //#########################################################

            unsigned char magic;
            char *s = "Maki";
            unsigned int ps2;
            char s2[96];
            char s3[96];
            char s4[96];
            unsigned char buf[1024];

            char maki2[1024];

            //structToSend->send(hsock);
            //cout << "maki2 = " << strlen((const char*)maki2) << endl;

            if( (bytecount=recv(csock, (void*)maki2, 1024,0)) < 1)
            {
                fprintf(stderr, "recv_Data Error reciving data %d\n", errno);
                //goto FINISH;
                exitClient(hsock);
                return -1;
            }


            memcpy((unsigned char*)buf, maki2, 1024);

            unpack((unsigned char*)buf, "CHsss",    &magic,
                                            &ps2,
                                            &s2,
                                            &s3,
                                            &s4);

            printf("recv: '%c' %hhu %s %s %s\n",   magic,
                                     ps2,
                                     s2,
                                     s3,
                                     s4);

            cout << configuration[0].name.data()<< s2 << endl;
            cout << configuration[1].name.data()<< s2 << endl;
            cout << configuration[2].name.data()<< s2 << endl;
            //#########################################################

            int existProcess = 0;
            int activeProcess = 0;
            int process2Active = -1;


            for( int i = 0; i < numProcess ; i++)
            {
                if(configuration[i].name.compare(s2) == 0)
                {
                    cout << "encontre el proceso a encender = " << s2 << endl;
                    process2Active = i;
                }
            }

            //#########################################################################

            if(process2Active > -1) //(configuration[i].name.compare(s2) == 0) && (configuration[i].active == 0))
            {
                cout << "active =" << configuration[process2Active].active << endl;
                if(configuration[process2Active].active == 0)
                {
                    configuration[process2Active].active = 1;
                    existProcess = 1;
                    activeProcess = 1;

                    cout << "Configurando hilo " << s2 << endl;
                    processThread.name = configuration[process2Active].name;
                    processThread.IP_RTAI = configuration[process2Active].IP_RTAI;
                    processThread.Node2RTAI = configuration[process2Active].Node2RTAI;
                    processThread.PORT_RTAI = configuration[process2Active].PORT_RTAI;
                    processThread.RTAI2Node = configuration[process2Active].RTAI2Node;
                    processThread.SHM = configuration[process2Active].SHM;

                    processThread.csock = configuration[process2Active].csock = csock;


                    //##########################################################
                    unsigned int packetsize, ps2;
                    char *s = "Maki";
                    char s2[96];
                    char s3[96];
                    char s4[96];
                    char buffer[1024];
                    packetsize = pack(buf, "CHs", 'A', 0, "Existe el proceso");

                    packi16(buf+1, packetsize);


                    memcpy((unsigned char*)buffer, buf, packetsize);


                    if( (bytecount=send(csock, (void*)buffer, 1024,0)) < 1)
                    {
                        fprintf(stderr, "recv_Data Error reciving data %d\n", errno);
                        //goto FINISH;
                        exitClient(hsock);
                        return -1;
                    }

                    unpack((unsigned char*)buffer, "CHs",    &magic,
                                                            &ps2,
                                                            &s2);

                    printf("send: '%c' %hhu %s\n",   magic,
                                                     ps2,
                                                     s2);
                //################################################################
                /*
                    //processFind = 1;
                    strcpy(buffer, "Creando proceso");
                    if((bytecount = send(csock, buffer, strlen(buffer), 0))== -1){
                        fprintf(stderr, "Error sending data %d\n", errno);
                        //goto FINISH;
                    }

                    cout << "---------------------------" << endl;

                */
                    // creacion del hilo
                    //pthread_create( &thread_id, 0, &AaronMR_S::SocketHandler, (void*)&processThread);
                    pthread_create( &thread_id, 0, &AaronMR_S::SocketHandler, (void*)&configuration[process2Active]);
                    pthread_detach(thread_id);



                }else{
                    cout << "el proceso esta activo, lo sentimos" << endl;

                    unsigned int packetsize, ps2;
                    char *s = "Maki";
                    char s2[96];
                    char s3[96];
                    char s4[96];
                    char buffer[1024];
                    packetsize = pack(buf, "CHs", 'E', 0, "Proceso Activo");

                    packi16(buf+1, packetsize);


                    memcpy((unsigned char*)buffer, buf, packetsize);


                    if( (bytecount=send(csock, (void*)buffer, 1024,0)) < 1)
                    {
                        fprintf(stderr, "recv_Data Error reciving data %d\n", errno);
                        //goto FINISH;
                        exitClient(hsock);
                        return -1;
                    }

                    unpack((unsigned char*)buffer, "CHs",    &magic,
                                                            &ps2,
                                                            &s2);

                    printf("send: '%c' %hhu %s\n",   magic,
                                                     ps2,
                                                     s2);

                }


            }


            //#########################################################################

            /*
            for( int i = 0; i < numProcess ; i++)
            {

                if((configuration[i].name.compare(s2) == 0) && (configuration[i].active == 0))
                {
                    existProcess = 1;
                    activeProcess = 1;

                    cout << "Configurando hilo " << s2 << endl;
                    processThread.name = configuration[i].name;
                    processThread.IP_RTAI = configuration[i].IP_RTAI;
                    processThread.Node2RTAI = configuration[i].Node2RTAI;
                    processThread.PORT_RTAI = configuration[i].PORT_RTAI;
                    processThread.RTAI2Node = configuration[i].RTAI2Node;
                    processThread.SHM = configuration[i].SHM;

                    processThread.csock = configuration[i].csock = csock;


                    //##########################################################
                    unsigned int packetsize, ps2;
                    char *s = "Maki";
                    char s2[96];
                    char s3[96];
                    char s4[96];
                    char buffer[1024];
                    packetsize = pack(buf, "CHs", 'A', 0, "Existe el proceso");

                    packi16(buf+1, packetsize);


                    memcpy((unsigned char*)buffer, buf, packetsize);


                    if( (bytecount=send(csock, (void*)buffer, 1024,0)) < 1)
                    {
                        fprintf(stderr, "recv_Data Error reciving data %d\n", errno);
                        //goto FINISH;
                        exitClient(hsock);
                        return -1;
                    }

                    unpack((unsigned char*)buffer, "CHs",    &magic,
                                                            &ps2,
                                                            &s2);

                    printf("send: '%c' %hhu %s\n",   magic,
                                                     ps2,
                                                     s2);
                //################################################################

                //   //processFind = 1;
                //    strcpy(buffer, "Creando proceso");
                //    if((bytecount = send(csock, buffer, strlen(buffer), 0))== -1){
                //        fprintf(stderr, "Error sending data %d\n", errno);
                //        //goto FINISH;
                //    }

                //    cout << "---------------------------" << endl;


                    // creacion del hilo
                    pthread_create( &thread_id, 0, &AaronMR_S::SocketHandler, (void*)&processThread);
                    pthread_detach(thread_id);



                }
            }
            */

            if(existProcess == 0)
            {
                cout << "no existe el proceso con nombre " << s2 << endl;
                unsigned int packetsize, ps2;
                char *s = "Maki";
                char s2[96];
                char s3[96];
                char s4[96];
                char buffer[1024];
                packetsize = pack(buf, "CHs", 'E', 0, "no existe");

                packi16(buf+1, packetsize);


                memcpy((unsigned char*)buffer, buf, packetsize);


                if( (bytecount=send(csock, (void*)buffer, 1024,0)) < 1)
                {
                    fprintf(stderr, "recv_Data Error reciving data %d\n", errno);
                    //goto FINISH;
                    //exitClient(hsock);
                    return -1;
                }

                unpack((unsigned char*)buffer, "CHs",    &magic,
                                                        &ps2,
                                                        &s2);

                printf("send: '%c' %hhu %s\n",   magic,
                                                 ps2,
                                                 s2);
            }

            if(activeProcess == 0)
            {
                cout << "el proceso ya esta activo " << s2 << endl;
                unsigned int packetsize, ps2;
                char *s = "Maki";
                char s2[96];
                char s3[96];
                char s4[96];
                char buffer[1024];
                packetsize = pack(buf, "CHs", 'E', 0, "proceso activo");

                packi16(buf+1, packetsize);


                memcpy((unsigned char*)buffer, buf, packetsize);


                if( (bytecount=send(csock, (void*)buffer, 1024,0)) < 1)
                {
                    fprintf(stderr, "recv_Data Error reciving data %d\n", errno);
                    //goto FINISH;
                    //exitClient(hsock);
                    return -1;
                }

                unpack((unsigned char*)buffer, "CHs",    &magic,
                                                        &ps2,
                                                        &s2);

                printf("send: '%c' %hhu %s\n",   magic,
                                                 ps2,
                                                 s2);
            }










		}
		else{
			fprintf(stderr, "Error accepting %d\n", errno);
			exitClient(hsock);
		}

	//}

}
Esempio n. 10
0
/**
 * Author: 	 	Joel Denke, Marcus Isaksson
 * Description:		Run the game on client
 */
int main(int argc, char *argv[])
{
	int i, j, no, yb, keysHeld[323] = {0};
	int result = 0;
	SDL_Thread * eventBuffer;
	SDL_Thread * runBuffer;
	struct timer_t2 fps;
	
	char * server_ip = malloc(sizeof(char) * 16);
	char * elem = malloc(sizeof(char) * MESSAGE_SIZE);

	pColor = malloc(sizeof(SDL_Color));
	oColor = malloc(sizeof(SDL_Color));
	connection = malloc(sizeof(connection_data));

	for (i = 0; i < NO_BUFFERS; i++) {
		cb[i] = malloc(sizeof(cBuffer));
		b_lock[i] = SDL_CreateMutex();
	}

	strcpy(server_ip, "127.0.0.1");

	pColor->r = 0;
	pColor->g = 255;
	pColor->b = 255;
	oColor->r = 0;
	oColor->g = 0;
	oColor->b = 255;

	initGraphics();
	initSound();

	printf("Render menu\n");
	graphicsMenu(&gameWorld, server_ip);

	initSlots(cb[0], BUFFER_SIZE);
	initSlots(cb[1], NO_OBJECTS);
	initSlots(cb[2], BUFFER_SIZE);

	state = gStart;

	if (clientConnect(connection, server_ip) == 0)
	{
		eventBuffer = SDL_CreateThread(listenEventBuffer, &connection);

		while (1) {
			switch (state) {
				case gStart:
					runData(2);
					break;
				case gInit:
					timer_start(&fps);
					startDraw();
					drawLoadScr(SCREEN_WIDTH, SCREEN_HEIGHT);
					endDraw();

					initWorld();
					
					if (timer_get_ticks(&fps) < 1000 / FPS)
					{
						//delay the as much time as we need to get desired frames per second
						SDL_Delay( ( 1000 / FPS ) - timer_get_ticks(&fps) );
					}
					break;
				case gRunning :
					timer_start(&fps);
					drawGraphics();
					listenInput(keysHeld);

					// i = 0: players; i = 1: objects; i = 2: messages
					for (i = 0; i < NO_BUFFERS; i++) {
						runData(i);
					}

					if (timer_get_ticks(&fps) < 1000 / FPS)
					{
						//delay the as much time as we need to get desired frames per second
						SDL_Delay( ( 1000 / FPS ) - timer_get_ticks(&fps) );
					}

					break;
				case gExit :
					//sprintf(string, "%d,quit", connection->client_id);
					printf("Freeing music now\n");
					pauseMusic();
					freeMusic();
					end_session(connection);
					printf("Player is exit game now\n");
					exitClient(eventBuffer);
					break;
				default :
					printf("test\n");
					break;
			}
		}
	} else {
		printf("Misslyckade med att kontakta servern på ip-adress: '%s'\n", server_ip);
		state = gExit;
		pauseMusic();
		freeMusic();
		exitClient(eventBuffer);
	}

	return 0;
}
Esempio n. 11
0
int main(int argc, char *argv[]) {
   int i=0;
   int result;
   int port;
   int num_clients = 0;
   int server_sockfd, client_sockfd;
   struct sockaddr_in server_address;
   int addresslen = sizeof(struct sockaddr_in);
   int fd;
   char fd_array[MAX_CLIENTS];
   fd_set readfds, testfds, clientfds;
   char msg[MSG_SIZE + 1];     
   char kb_msg[MSG_SIZE + 10]; 
      

   /*Serwer==================================================*/
   if(argc==1 || argc == 3){
     if(argc==3){
       if(!strcmp("-p",argv[1])){
         sscanf(argv[2],"%i",&port);
       }else{
         printf("Nieprawidlowe wywolanie\n");
         exit(0);
       }
     }else port=MYPORT;
     
     printf("\n*** Uruchamianie serwera (wpisz quit aby zakonczyc): \n");
     fflush(stdout);

     /* Socket dla serwera */
     server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
     server_address.sin_family = AF_INET;
     server_address.sin_addr.s_addr = htonl(INADDR_ANY);
     server_address.sin_port = htons(port);
     bind(server_sockfd, (struct sockaddr *)&server_address, addresslen);

     /* Kolejka polaczen, inicjalizacja zestawu deskryptorow */
     listen(server_sockfd, 1);
     FD_ZERO(&readfds);
     FD_SET(server_sockfd, &readfds);
     FD_SET(0, &readfds);  /* Klawiatura */

     /*  Oczekiwanie na klientow */
     while (1) {
        testfds = readfds;
        select(FD_SETSIZE, &testfds, NULL, NULL, NULL);
                    
        /* Jesli nastepuje aktywnosc sprawdzamy gdzie przy uzyciu FD_ISSET */
        for (fd = 0; fd < FD_SETSIZE; fd++) {
           if (FD_ISSET(fd, &testfds)) {
              
              if (fd == server_sockfd) { /* Zaakceptowanie nowego polaczenia */
                 client_sockfd = accept(server_sockfd, NULL, NULL);
                
                                
                 if (num_clients < MAX_CLIENTS) {
                    FD_SET(client_sockfd, &readfds);
                    fd_array[num_clients]=client_sockfd;
                    /*ID klienta*/
                    printf("Klient %d polaczony\n",num_clients++);
                    fflush(stdout);
                    
                    sprintf(msg,"M%2d",client_sockfd);
                    /*wyslij ID klienta */
                    send(client_sockfd,msg,strlen(msg),0);
                 }
                 else {
                    sprintf(msg, "Zbyt wiele klientow. Sprobuj pozniej.\n");
                    write(client_sockfd, msg, strlen(msg));
                    close(client_sockfd);
                 }
              }
              else if (fd == 0)  {  /* obsluga klawiatury */                 
                 fgets(kb_msg, MSG_SIZE + 1, stdin);
                 if (strcmp(kb_msg, "quit\n")==0) {
                    sprintf(msg, "Serwer sie zamyka\n");
                    for (i = 0; i < num_clients ; i++) {
                       write(fd_array[i], msg, strlen(msg));
                       close(fd_array[i]);
                    }
                    close(server_sockfd);
                    exit(0);
                 }
                 else {
                    sprintf(msg, "M%s", kb_msg);
                    for (i = 0; i < num_clients ; i++)
                       write(fd_array[i], msg, strlen(msg));
                 }
              }
              else if(fd) {  /*obsluga aktywnosci klientow*/
                 //odczyt z otwartego sockeetu
                 result = read(fd, msg, MSG_SIZE);
                 
                 if(result==-1) perror("read()");
                 else if(result>0){
                    /*odczyt id klienta*/
                    sprintf(kb_msg,"M%2d",fd-4);
                    msg[result]='\0';
                    
					if(msg[0]=='p' && msg[1]=='l' && msg[2]=='i' && msg[3] == 'k')
					{
						flaga=1;
					}
					
                    /*sklejenie id i wiadomosci w jeden string*/
					strcat(kb_msg," ");
                    strcat(kb_msg,msg);                                        
                    
                    /*wypisanie do innych klientow*/
					if(flaga==0)
					{
						for(i=0;i<num_clients;i++){
						   if (fd_array[i] != fd)  /*nie piszemy do tego kto wyslal wiadomosc*/
							  write(fd_array[i],kb_msg,strlen(kb_msg));
						}
						/*wypisanie na serwerze*/
						printf("%s",kb_msg+1);
					}
					else if (flaga==1)
					{						
						odbierzPlik(client_sockfd);
						for(i=0;i<num_clients;i++){
						   if (fd_array[i] != fd)  
							  wyslijPlik(fd_array[i]);
						}
						flaga=0;
					}						
                     /*wylaczenie klienta*/
                    if(msg[0] == 'X'){
                       exitClient(fd,&readfds, fd_array,&num_clients);
                    }   
                 }                                   
              }                  
              else { 
                 exitClient(fd,&readfds, fd_array,&num_clients);
              }//if
           }//if
        }//for
     }//while
  }//koniec kodu serwera

}//main
Esempio n. 12
0
int main(int argc, char *argv[]) {
  int i=0;
  int result;
  struct message msg;

  struct sockaddr_in server_address;
  int addresslen = sizeof(struct sockaddr_in);
  int fd;

  FILE *f;

  /*Server==================================================*/
  if(argc != 1){
    printf("Sai tham số.\nUsage: server\n");
    exit(0);
  }

  printf("\n*** Server đang khởi động (enter \"quit\" to stop): \n");
  fflush(stdout);

  /* Create and name a socket for the server */
  server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
  server_address.sin_family = AF_INET;
  server_address.sin_addr.s_addr = htonl(INADDR_ANY);
  server_address.sin_port = htons(MYPORT);
  bind(server_sockfd, (struct sockaddr *)&server_address, addresslen);

  /* Create a connection queue and initialize a file descriptor set */
  listen(server_sockfd, 1);
  FD_ZERO(&readfds);
  FD_SET(server_sockfd, &readfds);
  FD_SET(0, &readfds);  /* Add keyboard to file descriptor set */

  if ((f=fopen("request","w")) != NULL){
    fclose(f);
  }

  /* init shared memory segment */
  if ((key = ftok("request", 'B')) == -1) {
    perror("ftok");
    exit(1);
  }

  if ((msqid = msgget(key, 0644 | IPC_CREAT)) == -1) {
    perror("msgget");
    exit(1);
  }

  pthread_create(&liftCtrl_thr, NULL, liftCtrlCallback, NULL);


  /*  Now wait for clients and requests */
  while (1) {
    testfds = readfds;
    select(FD_SETSIZE, &testfds, NULL, NULL, NULL);

    /* If there is activity, find which descriptor it's on using FD_ISSET */
    for (fd = 0; fd < FD_SETSIZE; fd++) {
      if (FD_ISSET(fd, &testfds)) {
        if (fd == server_sockfd) { /* Accept a new connection request */
          client_sockfd = accept(server_sockfd, NULL, NULL);

          if (num_clients < MAX_CLIENTS) {
            // Add new clientfd to file descriptor set
            FD_SET(client_sockfd, &readfds);
            client_array[num_clients++].sockfd = client_sockfd;

            setupMessage( &msg, CONNECT_ACCEPTED, 0);
            write(client_sockfd, &msg, sizeof(struct message));
          } else {
            printf("Quá nhiều kết nối\n");
            setupMessage(&msg, CONNECT_REJECTED, 0);
            write(client_sockfd, &msg, sizeof(struct message));
            close(client_sockfd);
            }
          } else if (fd == 0)  {  /* Process keyboard activity */
          char mess[30];
          fgets(mess, 100, stdin);
          mess[strlen(mess) - 1] = '\0'; // remove \newline char
          if (strcmp(mess, "quit")==0) {
            setupMessage(&msg, SHUTDOWN_SERVER, 0);
            for (i = 0; i < num_clients ; i++) {
              write(client_array[i].sockfd, &msg, sizeof(struct message));
            }

            for (i = 0; i < num_clients ; i++) {
              close(client_array[i].sockfd);
              FD_CLR(client_array[i].sockfd, &readfds);
            }
            close(server_sockfd);
            FD_CLR(server_sockfd, &readfds);

            if (msgctl(msqid, IPC_RMID, NULL) == -1) {
              perror("msgctl");
            }

            exit(0);
          }
        } else if(fd) {  /*Process Client specific activity*/
          //read data from open socket
          result = read(fd, &msg, sizeof(struct message));

          if(result == -1) perror("read()");
          else {
            int code = msg.type;

            switch(code){
              case REQUEST_SHUTDOWN:
                printf("Client đang đóng \n");
                exitClient(fd, &readfds, client_array, &num_clients);
                break;
              /**
               * Request from floor controler
               */
              case REQUEST_JOIN:
                for (i = 0; i < num_clients; i++){
                  if (client_array[i].sockfd == fd){
                    client_array[i].clientType = CLIENT_FLOOR;
                    client_array[i].clientInfo = (int)msg.floor;                    
                    break;
                  }
                }
                setupMessage(&msg, JOIN_ACCEPTED, 0);
                write(fd, &msg, sizeof (struct message));
                break;
              case REQUEST_FLOOR:
                printf("Tầng %d được gọi\n", (int)msg.floor);
                sendMsgRequest(msg);
                break;
              /**
               * Request from elevator controler
               */
              case ELEVATOR_REQUEST_JOIN:
                for (i = 0; i < num_clients; i++){
                  if (client_array[i].sockfd == fd){
                    client_array[i].clientType = CLIENT_ELEVATOR;
                    elevator_sockfd = fd;
                    break;
                  }
                }
                setupMessage(&msg, JOIN_ACCEPTED, 0);
                write(fd, &msg, sizeof(struct message));
                break;
              case ELEVATOR_REQUEST_SUCCESS:
              case ELEVATOR_REQUEST_UPDATE:
                sendMsgNotify(msg);
                break;
              default:
                break;
            }
          }
        }
      }//if
    }//for
  }//while

  return 1;
}//main
Esempio n. 13
0
void RenderAf::v_action( Action & i_action)
{
	const JSON & operation = (*i_action.data)["operation"];
	if( operation.IsObject())
	{
		std::string type;
		af::jr_string("type", type, operation);
		if( type == "exit")
		{
			if( false == isOnline()) return;
			appendLog("Exit by " + i_action.author);
			exitClient("exit", i_action.jobs, i_action.monitors);
			return;
		}
		else if( type == "launch_cmd")
		{
			if( false == isOnline()) return;
			std::string cmd;
			if( af::jr_string("cmd", cmd, operation))
			{
				bool exit = false;
				af::jr_bool("exit", exit, operation);
				if( exit )
					appendLog("Launch command and exit request by " + i_action.author + "\n" + cmd);
				else
					appendLog("Launch command request by " + i_action.author + "\n" + cmd);
				launchAndExit( cmd, exit, i_action.jobs, i_action.monitors);
			}
			else
			{
				appendLog("Launch command exit request by " + i_action.author + "has no 'cmd'");
			}
			return;
		}
		else if( type == "eject_tasks")
		{
			if( false == isBusy()) return;
			appendLog("Task(s) ejected by " + i_action.author);
			ejectTasks( i_action.jobs, i_action.monitors, af::TaskExec::UPEject);
			return;
		}
		else if( type == "eject_tasks_keep_my")
		{
			if( false == isBusy()) return;
			appendLog("Task(s) ejected keeping own by " + i_action.author);
			ejectTasks( i_action.jobs, i_action.monitors, af::TaskExec::UPEject, &i_action.user_name);
			return;
		}
		else if( type == "delete")
		{
			if( isOnline() ) return;
			appendLog( std::string("Deleted by ") + i_action.author);
			offline( NULL, 0, i_action.monitors, true);
//AFCommon::QueueDBDelItem( this);
			return;
		}
		else if( type == "reboot")
		{
			if( false == isOnline() ) return;
			appendLog( std::string("Reboot computer by ") + i_action.author);
			exitClient("reboot", i_action.jobs, i_action.monitors);
			return;
		}
		else if( type == "shutdown")
		{
			if( false == isOnline() ) return;
			appendLog( std::string("Shutdown computer by ") + i_action.author);
			exitClient("shutdown", i_action.jobs, i_action.monitors);
			return;
		}
		else if( type == "wol_sleep")
			wolSleep( i_action.monitors);
		else if( type == "wol_wake")
			wolWake( i_action.monitors);
		else if( type == "service")
		{
			af::RegExp service_mask; bool enable;
			af::jr_regexp("name", service_mask, operation);
			af::jr_bool("enable", enable, operation);
			for (int i = 0 ; i < m_host.getServicesNum() ; ++i)
			{
				std::string service = m_host.getServiceName(i);
				if( service_mask.match( service))
					setService( service, enable);
			}
		}
		else if( type == "restore_defaults")
		{
			m_max_tasks = -1;
			m_capacity = -1;
			m_services_disabled.clear();
			disableServices(); // Dirty check exists in that function
		}
		else
		{
			appendLog("Unknown operation \"" + type + "\" by " + i_action.author);
			return;
		}
		appendLog("Operation \"" + type + "\" by " + i_action.author);
		i_action.monitors->addEvent( af::Monitor::EVT_renders_change, m_id);
		store();
		return;
	}

	const JSON & params = (*i_action.data)["params"];
	if( params.IsObject())
		jsonRead( params, &i_action.log);

	if( i_action.log.size() )
	{
		store();
		i_action.monitors->addEvent( af::Monitor::EVT_renders_change, m_id);
	}
}
Esempio n. 14
0
int main(int argc, char *argv[]) 
{
    int i=0;
    int count=0;
    char pass[1];
    int port,result;
    int num_clients = 0;
    int server_sockfd, client_sockfd;
    struct sockaddr_in server_address;
    int addresslen = sizeof(struct sockaddr_in);
    int fd;
    char fd_array[MAX_CLIENTS];
    fd_set readfds, testfds, clientfds;
    char msg[MSG_SIZE + 1];     
    char kb_msg[MSG_SIZE + 10];       
 
    /*Server*/
 
    if(argc==1 || argc == 3){
        if(argc==3){
            if(!strcmp("-p",argv[1])){
                sscanf(argv[2],"%i",&port);
            }
            else{
            printf("Invalid parameter.\nUsage: chat [-p PORT] HOSTNAME\n");
            exit(0);
            }
        }
        else
            port=MYPORT;
    printf("\n\t******************** iBOT Server ********************\n");
    printf("\n\n\t Authentication :\n\n\t Password :    "******"%s",&pass);
    if(strcmp(pass,"cyber")!=0){
        printf("\n\n !! failure !!\n\n " ); 
        exit(0);
    } 
    printf("\n*** Server waiting (enter \"quit\" to stop): \n");
    fflush(stdout);
 
    /* Create and name a socket for the server */
 
    server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
    server_address.sin_family = AF_INET;
    server_address.sin_addr.s_addr = htonl(INADDR_ANY);
    server_address.sin_port = htons(port);
    bind(server_sockfd, (struct sockaddr *)&server_address, addresslen);
 
    /* Create a connection queue and initialize a file descriptor set */
 
    listen(server_sockfd, 1);
    FD_ZERO(&readfds);
    FD_SET(server_sockfd, &readfds);
    FD_SET(0, &readfds);    /* Add keyboard to file descriptor set */
 
    /* Now wait for clients and requests */
 
    while (1){
        testfds = readfds;
        select(FD_SETSIZE, &testfds, NULL, NULL, NULL);
                     
        /* If there is activity, find which descriptor it's on using FD_ISSET */
 
        for (fd = 0; fd < FD_SETSIZE; fd++) {    
            if (FD_ISSET(fd, &testfds)) {
                if (fd == server_sockfd) {  /* Accept a new connection request */
                    client_sockfd = accept(server_sockfd, NULL, NULL);      
                    if (num_clients < MAX_CLIENTS) {
                        FD_SET(client_sockfd, &readfds);
                        fd_array[num_clients]=client_sockfd;
  
                        /*Client ID*/
 
                        printf("\n -> Bot No. %d standby for orders\n",++num_clients);
                        printf("\n >> ");
                        fflush(stdout);
                        send(client_sockfd,msg,strlen(msg),0);
                    }
                    else{
                        sprintf(msg, "XSorry, too many clients.  Try again later.\n");
                        write(client_sockfd, msg, strlen(msg));
                        close(client_sockfd);
                    }
                }
                else
                    if (fd == 0){ 
                        printf(" >> ");       /* Process keyboard activity */                
                        fgets(kb_msg, MSG_SIZE + 1, stdin);       
                        if (strcmp(kb_msg, "quit\n")==0) {
                            sprintf(msg, "iBot Server is shutting down.\n");
                            for (i = 0; i < num_clients ; i++) {
                                write(fd_array[i], msg, strlen(msg));
                                close(fd_array[i]);
                            }
                            close(server_sockfd);
                            exit(0);
                        }
                        else{
                            sprintf(msg, "M%s", kb_msg);
                            for (i = 0; i < num_clients ; i++)
                                write(fd_array[i], msg, strlen(msg));
                        }
                    }
                    else
                        if(fd){                 
                            result = read(fd, msg, MSG_SIZE);   /*read data from open socket*/             
                            if(result==-1) 
                                perror("read()");
                            else
                                if(result>0){
                                    sprintf(kb_msg,"MClient CID %2d",fd);   /*read 2 bytes client id*/
                                    msg[result]='\0';
                     
                            /*concatinate the client id with the client's message*/
       
                                strcat(kb_msg," ");
                                strcat(kb_msg,msg+1);                                        
                     
                            /*print to other clients*/
 
                                for(i=0;i<num_clients;i++){
                                    if (fd_array[i] != fd)                     /*dont write msg to same client*/
                                        write(fd_array[i],kb_msg,strlen(kb_msg));
                                }
                     
                            /*print to server  */
 
                                printf("%s",kb_msg+1);
                     
                            /*Exit Client*/
 
                                if(msg[0] == 'X'){
                                    exitClient(fd,&readfds, fd_array,&num_clients);
                                }   
                            }                                   
                        }                  
                        else{                           
                            exitClient(fd,&readfds, fd_array,&num_clients);  /* A client is leaving */
                        }
            }
        }
    }
  }
}
Esempio n. 15
0
void BtsSpawnClient::killClient()
{
	exitClient(true);
}
Esempio n. 16
0
void BtsSpawnClient::exitClient()
{
	exitClient(false);
}