質問

I haven't been able to find a similar issue, so here goes:

I'm sending a QString from a QLocalSocket to a QLocalServer across two applications. The receiving (QLocalServer) application does receive the message, but it seems the encoding is completely wrong.

If I send a QString = "x" from the QLocalSocket (client), I'm getting a foreign (Chinese?) symbol in the QLocalServer. My code is literally copied from the Nokia Developer website

If I printout the message via QDebug, I get "??". If I fire it in a message box, Chinese characters are printed. I've tried re-encoding the received message to UTF-8, Latin1, etc., with no luck.

Code is as follows:

//Client
int main(int argc, char *argv[])
{
QLocalSocket * m_socket = new QLocalSocket();
m_socket->connectToServer("SomeServer");

if(m_socket->waitForConnected(1000))
{
    //send a message to the server
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_7);
    out << "x";
    out.device()->seek(0);
    m_socket->write(block);
    m_socket->flush();
    QMessageBox box;
    box.setText("mesage has been sent");
    box.exec();
...
}

//Server - this is within a QMainWindow
void MainWindow::messageReceived()
{
QLocalSocket *clientConnection = m_pServer->nextPendingConnection();

while (clientConnection->bytesAvailable() < (int)sizeof(quint32))
    clientConnection->waitForReadyRead();


connect(clientConnection, SIGNAL(disconnected()),
        clientConnection, SLOT(deleteLater()));

QDataStream in(clientConnection);
in.setVersion(QDataStream::Qt_4_7);
if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) {
    return;
}

QString message;
in >> message;

QMessageBox box;
box.setText(QString(message));
box.exec();
}

Any help is highly appreciated.

役に立ちましたか?

解決

The client is serializing a const char* while the server is deserializing a QString. These aren't compatible. The former literally writes the string bytes, the latter first encodes to UTF-16. So, I guess on the server side, the raw string data "fff" is being decoded into a QString as though it were UTF-16 data... perhaps resulting in character U+6666, 晦.

Try changing the client to also serialize a QString, i.e.

// client writes a QString
out << QString::fromLatin1("fff");

// server reads a QString
QString message;
in >> message;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top