示例#1
0
void MainWindow::validateConnection()
{
    if(ui->IPAddress->text().length() < 7)
    {
        QMessageBox msg;
        msg.setWindowTitle("Error");
        msg.setText("Skřítek v počítači přenesl data IP adresy a zjistil, že je prázdná nebo neni úplná.");
        msg.setIcon(QMessageBox::Information);

        msg.exec();

        return;
    }

    if(ui->ServerPort->text().length() < 1)
    {
        QMessageBox msg;
        msg.setWindowTitle("Error");
        msg.setText("Skřítek v počítači přenesl data cílového portu a zjistil, že je port prázdný. Port je třeba vyplnit, aby věděl kam má doručit data");
        msg.setIcon(QMessageBox::Information);

        msg.exec();

        return;
    }

    Client* client = new Client(ui->IPAddress->text(), ui->ServerPort->text().toInt(), this);

    if(client->connectToServer())
    {
        IP   = ui->IPAddress->text();
        port = ui->ServerPort->text().toInt();

        ui->action_rejoin->setEnabled(true);

        connect(ui->action_rejoin, SIGNAL(triggered()), this, SLOT(rejoin()));

        connect(client, SIGNAL(error(QString)), this, SLOT(showError(QString)));

        // Say hello to server
        client->sendPacket(Hello, QString("Hello"), client->toData(47777));

        setCentralWidget(NULL);

        if(surface)
            delete surface;

        surface = new Surface(client, this);

        setCentralWidget(surface);

        connect(this, SIGNAL(key(Qt::Key&)), surface, SLOT(keyPress(Qt::Key&)));

        connect(surface, SIGNAL(foodEaten()), this, SLOT(updateScore()));
        connect(surface, SIGNAL(gameOver()),  this, SLOT(gameOver()));

        score = -1;

        updateScore();
    }
示例#2
0
bool
ServerRoom::join( ClientConnection* clientConnection, const std::string& name, const std::string& password, int& chairIndex )
{
    // REFACTOR - this code and rejoin() have a LOT in common

    // This could be a rejoin - find the human by name.
    HumanPlayer* humanPlayer = getHumanPlayer( name );
    if( humanPlayer  )
    {
        mLogger->debug( "join: rejoining existing player to room" );
        return rejoin( clientConnection, name );
    }

    if( !mPassword.empty() && (password != mPassword) )
    {
        sendJoinRoomFailureRsp( clientConnection, proto::JoinRoomFailureRsp::RESULT_INVALID_PASSWORD, mRoomId );
        return false;
    }

    int playerIdx = getNextAvailablePlayerIndex();
    if( playerIdx == -1 )
    {
        sendJoinRoomFailureRsp( clientConnection, proto::JoinRoomFailureRsp::RESULT_ROOM_FULL, mRoomId );
        return false;
    }
    chairIndex = playerIdx;

    HumanPlayer *human = new HumanPlayer( playerIdx, mDraftPtr, mLoggingConfig.createChildConfig( "humanplayer" ), this );
    connect( human, &HumanPlayer::readyUpdate, this, &ServerRoom::handleHumanReadyUpdate );
    connect( human, &HumanPlayer::deckUpdate, this, &ServerRoom::handleHumanDeckUpdate );
    human->setName( name );
    human->setClientConnection( clientConnection );
    mClientConnectionMap.insert( clientConnection, human );
    mHumanList.append( human );
    mPlayerList[playerIdx] = human;
    mChairStateList[playerIdx] = CHAIR_STATE_STANDBY;
    mLogger->debug( "joined human {} with connection {} to player map at index {}:",
            (std::size_t)human, (std::size_t)clientConnection, playerIdx );
    for( int i = 0; i < mPlayerList.count(); ++i )
    {
        mLogger->debug( "   {}", (std::size_t)(mPlayerList[i]) );
    }

    // With at least one connection don't let the room expire.
    mRoomExpirationTimer->stop();

    // The human must observe the draft to get the observation callbacks.
    mDraftPtr->addObserver( human );

    // Inform the client that the room join was successful.
    sendJoinRoomSuccessRspInd( clientConnection, mRoomId, false, chairIndex );

    emit playerCountChanged( getPlayerCount() );

    // Inform all client connections of the room occupants changes.
    broadcastRoomOccupantsInfo();

    return true;
}
示例#3
0
/* Attempts to rejoin the room we were in prior to being disconnected
 * ASSUMES THAT WE ARE ALREADY RECONNECTED AND THAT THE ROOM NAME
 * IS IN server_room_name
 *
 * create is treated as a boolean -- to attempt creation of the room
 * or not
 * 
 * Since we're making a best effort, we'll only pass along failure
 * codes for errors we've not considered here. If there was no room for
 * us to create our room for instance, that is ok -- if there is a
 * network failure our caller should know */
int rejoin(char create) {
    int retries = RETRY_COUNT,
        pause = RETRY_PAUSE,
        ret = 0;

    /* Try switching to the room we were in */
    ret = retry_handler(handle_switch_room_req,
        server_room_name, &retries, &pause);

    switch (ret) {
        case COMMAND_SUCC:
            /* cool, done */
            return ret;
        case ZERO_ROOMS:
        case ROOM_NOT_FOUND:
            if (create) {
                /* try to recreate, then join */
                printf("Attempting to recreate room '%s'...\n",
                    server_room_name);
                ret = retry_handler(handle_create_room_req, server_room_name,
                    &retries, &pause);

                switch (ret) {
                    case COMMAND_SUCC:
                    case ROOM_EXISTS:
                        /* cool, retry join */
                        return rejoin(FALSE);
                    case MAX_ROOMS:
                    case ROOM_NAME_TOOOO_LOOOONG:
                        /* can't, oh well */
                        ret = 0;
                        break;
                    default:
                        fprintf(stderr, "Could not recreate room '%s'.\n",
                            server_room_name);
                        break;
                }
            }
            break;
        case ROOM_FULL:
            /* can't join */
            ret = 0;
            break;
        default:
            /* some other problem */
            fprintf(stderr, "Could not rejoin room '%s'.\n",
                server_room_name);
            break;
    }

    return ret;
}
示例#4
0
/*
 * Set up the client before accepting input.
 */
int init_client()
{
    int retries = RETRY_COUNT,
        pause = RETRY_PAUSE, 
        ret = 0;

    /* Make room for message buffer */
    if ((buf = (char *)malloc(MAX_MSG_LEN)) == 0) {
        fprintf(stderr, "%s: malloc failed\n", __func__);
        exit(1);
    }

    /* by casting, cmh points to the beginning of the memory block, and header
    * field values can then be directly assigned */
    cmh = (struct control_msghdr *)buf;
    
    /* set up connection tcp_hints */
    memset(&tcp_hints, 0, sizeof(tcp_hints));
    tcp_hints.ai_family = AF_INET;
    tcp_hints.ai_socktype = SOCK_STREAM;

#ifdef USE_LOCN_SERVER

    /* 0. Get server host name, port numbers from location server.
     *    See retrieve_chatserver_info() in client_util.c
     */
    if((retrieve_chatserver_info(server_host_name, &server_tcp_port,
        &server_udp_port) != 0))
    {
        /* Freak out, or retry or something */
        fprintf(stderr, "%s: error contacting location server\n", __func__);
        shutdown_clean(1);
    };

#endif

    /* stringify server ports for getaddrinfo */
    sprintf(server_tcp_port_str, "%d", server_tcp_port);
    sprintf(server_udp_port_str, "%d", server_udp_port);

    /********************************************
     * Initialization to allow UDP-based chat messages to chat server 
     */
    if ((ret = create_udp_sender()) != 0) {
        fprintf(stderr, "Could not create UDP socket\n");
        return ret;
    }
    
    /** Send register request ******************/
    while ((ret =
        retry_handler(handle_register_req, NULL, &retries, &pause))
        != 0)
    {
        switch (ret) {
            case NAME_IN_USE:
                // bump name, try again
                bump_username();
                break;
            case SERVER_FULL:
                shutdown_clean(0);
                break;
            default:
#ifdef USE_LOCN_SERVER
                /* Some communication error, try refreshing parameters
                 * from the locn server if we're using it */
                if((retrieve_chatserver_info(server_host_name,
                    &server_tcp_port, &server_udp_port) != 0))
                {
#endif 
                    // unrecoverable, die
                    shutdown_clean(1);
                    break;
#ifdef USE_LOCN_SERVER
                }
#endif
        }
    }

    /* If we successfully registered, see if we've got a room
     * name recorded -- if so we are reconnecting and we should
     * try to get back into that same room */
    if ((ret == 0) && (server_room_name[0] != 0)) {
        printf("Attempting to rejoin room '%s'...\n", server_room_name);
        ret = rejoin(TRUE);
    }

    return ret;
}