2012-10-25 45 views
1

我一直沒能找到一個類似的問題過程中損壞,所以這裏有雲:QLocalSocket到QLocalServer郵件傳輸

我在兩個應用程序發送從QLocalSocket爲QString到QLocalServer。接收(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

退房你發送的數據大小是否等於收到的大小。 – liuyanghejerry

+0

嗯,我已經添加了一個答案,但現在我在你的文本中看到你說你發送了'QString =「x」',但是在你的代碼中你發送了一個'const char * =「fff」'。這是什麼? – rohanpm

+0

我的錯誤,深夜。我已將const車*更改爲「x」 – giraffee

回答

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; 
+0

而且做到了!我太專注於接受任何收到的內容,並試圖對其進行重新編碼。謝謝! – giraffee