qlocalsocket到qlocalserver消息在转移期间被损坏

QLocalSocket to QLocalServer message being corrupted during transfer

本文关键字:损坏 转移 qlocalserver 消息 qlocalsocket      更新时间:2023-10-16

我找不到类似的问题,所以这里是:

我正在通过两个应用程序将QString从Qlocalsocket发送到Qlocalserver。接收(qlocalserver)应用程序确实会收到消息,但似乎编码是完全错误的。

如果我从qlocalsocket(客户端)发送QString =" X",我将在Qlocalserver中获得外国(中文?)符号。我的代码实际上是从诺基亚开发人员网站

复制的

如果我通过qdebug打印消息,我会得到"?"。如果我在消息框中发射它,则打印中文字符。我尝试将收到的消息重新编码给UTF-8,Latin1等,没有运气。

代码如下:

//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();
}

任何帮助都将受到高度赞赏。

客户端正在序列化const char*,而服务器则对QString进行序列化。这些不兼容。前者从字面上写了字符字节,后者首先编码为UTF-16。因此,我猜在服务器端,原始的字符串数据" FFF"被解码为QString,好像是UTF-16数据一样...也许导致字符u 6666,晦。

尝试更改客户端以序列化QString,即

// client writes a QString
out << QString::fromLatin1("fff");
// server reads a QString
QString message;
in >> message;