Search code examples
javaandroidqtstream

My client app reads unknown characters from QT Fortune Server example


I am trying to write an app on my Android device that connects to the QT Fortune Server example and displays results on my smartphone. Server is supposed to accept a connection, choose one fortune from the list of QStrings and send it to the connected client. Data is successfully sent to the client however there are some unknown characters in it when I try to read it. Server sends this data using following code:

void Server::sendFortune()
{
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_5_10);
    out << fortunes[QRandomGenerator::global()->bounded(fortunes.size())];
    QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
    connect(clientConnection, &QAbstractSocket::disconnected,
            clientConnection, &QObject::deleteLater);
    clientConnection->write(block);
        clientConnection->disconnectFromHost();
}

And my app reads this data using following code:

 try {
            mSocket = new Socket(serverIP, mPortNumber);
            InputStream inputStream = mSocket.getInputStream();
            Reader reader = new InputStreamReader(inputStream, Charset.forName("UTF-16"));
            char[] array = new char[50];
            reader.read(array);
            String fortune = new String(array);
            Log.i(TAG, fortune);
            mSocket.close();
            inputStream.close();
        }catch(java.io.IOException e){
            e.printStackTrace();
        }
        return null;

The example results look like this:

��^You cannot kill time without injuring eternity.��

��FYou've got to think about tomorrow.��������������������������

It looks like there are some unknown characters at the beginning of each fortune. I think the problem might be caused by improper use of streams as I'm not very familiar with them.

I would like to know how to get rid of these extra characters.


Solution

  • Do not use QDataStream as it handles an internal format (for example there are bytes that indicate the type of data, the lengths of the data, etc). Instead send the QString directly:

    clientConnection->write("Foo message");