Reputation: 972
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". (e.g. "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?
Upvotes: 0
Views: 2277
Reputation: 972
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.
Upvotes: 1