Hi,
the problem I need to solve, is related to the communication between a client and a server program. Communication is based on QTcpSocket class.
The client application send some command to the server... the server execute the command and maybe gives a reply to the server (not always, it depends on the command). Anyway...
To send commands I have written a function for every command, like this:
void Client::SomeCommand()
{
cmdId = 3;
tcpSocket->abort();
tcpSocket->waitForConnected(3000);
}
void Client::SomeCommand()
{
cmdId = 3;
tcpSocket->abort();
tcpSocket->connectToHost(QHostAddress::LocalHost, 2070);
tcpSocket->waitForConnected(3000);
}
To copy to clipboard, switch view to plain text mode
When the SIGNAL connected() is emitted, I execute the next slot:
void Client::sendCommand()
{
quint16 blocksize = 0;
switch(cmdId)
{
[...]
case 3:
command = "EXAMPLECOMMAND";
out << blocksize << reqId << command;
out.device()->seek(0);
out << quint16(block.size() - sizeof(quint16));
tcpSocket->write(block);
break;
[...]
default:
return;
}
cmdId = 0;
}
void Client::sendCommand()
{
quint16 blocksize = 0;
QString reqId = "REQ";
QString command;
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_5);
switch(cmdId)
{
[...]
case 3:
command = "EXAMPLECOMMAND";
out << blocksize << reqId << command;
out.device()->seek(0);
out << quint16(block.size() - sizeof(quint16));
tcpSocket->write(block);
break;
[...]
default:
return;
}
cmdId = 0;
}
To copy to clipboard, switch view to plain text mode
I posted only one command to clarify the structure.
If I call one command every much time, there is no problem... But if I call two commands very near in time, the signal connected() will not be emitted before the first command is really sent, so the connection of the first command is aborted and the cmdId variable is written with the value of the second command. As a result, I obtain that only the second command is sent!!!
Any idea on how to avoid this problem? Maybe this is not the best way to send commands... Have you got some suggestions on how to write better code?
Thank you very much.
Alex
Bookmarks