我无法找到类似的问题,所以请点击:
我正在跨两个应用程序从QLocalSocket向QLocalServer发送QString。接收(QLocalServer)应用程序确实收到了消息,但似乎编码完全错误。
如果我从QLocalSocket(客户端)发送QString =“x”,我在QLocalServer中得到一个外来(中文?)符号。我的代码完全是从Nokia Developer website
复制而来的如果我通过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();
}
非常感谢任何帮助。
答案 0 :(得分:4)
当服务器反序列化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;