Someone
Someone

Reputation: 41

Qt TCP socket - Write more that 15bytes

i have a problem with qt sockets...

I just created a TCP socket and i want to write a message on the server. All works fine but when i try to write a message that have more than 15 characters it's send's random thing ...

Here is how i create my socket : socket = new QTcpSocket(this);

and here where i use it :

bool MainWindow::loginAction(QString usernameNow, QString passwordNow) {
    QString logingRequestTmp = "LOGIN " + usernameNow + " " + passwordNow;
    const char* loginRequest= logingRequestTmp.toStdString().c_str();
    socket->write(loginRequest);
    return true;
}

So is there a simple way to say at socket->write() that i want to write more than 15bytes .?

Exemple :

with username = test and password = test

-> Server receive "LOGIN test test" (15 characters) works well !

But with with username = test1 and password = test

-> Server receive "���" (16 characters) not working well ...

Ps : When i try socket->write("123456789123456789") it works ... only don't work when i pass to socket->write() a const char* already created with 15+ characters

Upvotes: 1

Views: 283

Answers (1)

Peter
Peter

Reputation: 14937

String to byte conversion is no longer just "assume everything is 7-bit ASCII". It's better to be explicit about encoding, and the byproduct is that you get to stay in Qt land. Ditch the std::string() conversion.

I'd use the socket->write() overload that takes a QByteArray, which you can get from the original QString:

socket->write(logingRequestTmp.toUtf8());

or if you're not doing Utf, then any of the other QString functions that return QByteArrays work too: toLatin1(), for example.

Upvotes: 3

Related Questions