PDA

View Full Version : Using QLocalServer and QLocalSocket



danc81
10th November 2009, 12:09
Hi,

I'm working on an application which uses QLocalServer and QLocalSocket to communicate between processes which is not working quite as expected.

The client side is connecting like this:



socket.connectToServer("IPCCHANNEL");


In the slot connected to the connected() signal, we send the initial request data:



socket.write(reinterpret_cast<char*>(&m_nMessage), sizeof(int));
socket.flush();
socket.waitForReadyRead(20000);


In the slot connected to the readyRead() signal, we collect the returned information:



inputData.append(socket.readAll());


And finally, in the slot connected to the disconnected signal, we display the data and call qApp->exit(0).

From the server side, it works like this. In the slot attached to the incomingConnection() signal of the QLocalServer we get the new QLocalSocket connection and wait until it's ready to read the incoming request like this:



QLocalSocket *sock = localServer.nextPendingConnection();

if( !sock->waitForConnected() )
return;

if( !sock->waitForReadyRead() )
return;

QByteArray incoming(sock->readAll());


Then, once we have data to return, we send it back like this:



int length = response.length(); // response is a QByteArray
sock->write(reinterpret_cast<char*>(&length), sizeof(int));
sock->waitForBytesWritten(); // Send the return data length and wait for it to be written

int remaining = response.length();
int written = 0;
char *buf = response.data();
do {
written = sock->write(buf, remaining > 2048 ? 2048 : remaining);
buf += written;
remaining -= written;
} while( remaining && written && sock->waitForBytesWritten(5000) );

sock->flush();
sock->disconnectFromServer();
sock->deleteLater();


But this only seems to work occasionally, the initial request always makes it to the server and the server always writes the information back to the socket but sometimes not all the data arrives and mostly the disconnected() slot is never hit. I'm obviously missing something here, can anyone shed any light on the problem?