I want to make a console application that just connect to a server (using QTcpSocket), read some lines from it, send some data and exit.
This has to be done synchronously in just one function (at the beginning the connection is opened, at the end all data should have been sent and the connection is closed).
Can this be done?
I'm trying to do it, but I think I lose data sometimes. Also I have problems reading the data from server.
The code is more or less this way:
if (!socket->waitForConnected()) return false;
socket->waitForReadyRead();
if (socket->canReadLine()) {
line = ts->readLine();
}
// parse line
(*ts) << "Write some data\n";
(*ts) << "More data\n";
ts->flush();
socket->flush();
socket->waitForBytesWritten();
socket->close();
socket->disconnectFromHost();
socket->waitForDisconnected();
QTcpSocket * socket = new QTcpSocket(this);
QTextStream * ts = new QTextStream(socket);
socket->connectToHost( QHostAddress::LocalHost, port, QIODevice::ReadWrite);
if (!socket->waitForConnected()) return false;
socket->waitForReadyRead();
if (socket->canReadLine()) {
line = ts->readLine();
}
// parse line
(*ts) << "Write some data\n";
(*ts) << "More data\n";
ts->flush();
socket->flush();
socket->waitForBytesWritten();
socket->close();
socket->disconnectFromHost();
socket->waitForDisconnected();
To copy to clipboard, switch view to plain text mode
Is this correct?
It seems that sometimes the server doesn't get all lines.
Is it necessary to use a QTextStream?
Both QTextStream and QTcpSocket have a flush function, which one should I use?
I'm having problems reading the text from the server. It seems that I only get the first line. What's the right way to read from the server?
Bookmarks