简体   繁体   中英

C++ Qt - QTcpSocket emit readyRead() but canReadLine() always false

I am writing a client in C++ and a server in Python.

The server accepts the connection from the client, and sends to the client its player ID number, formated for the regular expression "id\\s\\d". (eg "id 3")

 if s is serversocket:
            print "Listening..."
            if accept_connection or nb_player < 5:
                connection, client_address = s.accept();
                print 'New connection from ', client_address
                connection.setblocking(0)
                inputs.append(connection)
        # Send player I to new connection
        connection.send("id "+str(len(inputs)-1))

The client initializes its socket, and connect. I implemented connected() to display a message on the GUI, if it is emitted. It is emitted without problem. Same thing on the server side, I receive the connection without issues.

Window::Window(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Window)
{
    ui->setupUi(this);

    /* Initialize socket */
    socket = new QTcpSocket(this);
    socket->connectToHost("localhost", 13456);

    connect(socket, SIGNAL(readyRead()), this, SLOT(data_received()));
    connect(socket, SIGNAL(connected()), this, SLOT(connected()));
}

The server receives data from the client without problem. It is the client that does not receive the information correctly.

void Window::data_received(){

    QRegExp id_re("id\\s(\\d)");

    while (socket->canReadLine()){
        /* Read line in socket (UTF-8 for accents)*/
        ui->log->append("listening...");
        QString line = QString::fromUtf8(socket->readLine()).trimmed();

        /* Player ID returned by server */
        if ( id_re.indexIn(line) != -1){
            //Test
            ui->log->append("The ID arrived");
            //Extract ID
            QString id_str = id_re.cap(1);
            //Put in data structure of player
            player->set_player_id(id_str);
            //Display message
            ui->log->append(QString("You are Player "+ player->get_player_id()));

        }
    }
}

get_player_id() returns a QString

I targeted my problem down, and it seems that canReadLine() is never returning true, therefore I can never read it. What could cause that?

It is because canReadLine() looks for "\\n" . Python does not automatically add it, therefore, there was no end-of-line to my string of character. Simply adding "\\n" in the Python code solved my problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM