I tried to modify the Qt
network tutorial, and implemented it like:
quint16 blockSize;
void Client::readData()
{
qDebug() << "Received Data!";
QByteArray data;
QDataStream in(tcpSocket);
in.setVersion(QDataStream::Qt_4_0);
if (blockSize == 0) {
if (tcpSocket->bytesAvailable() < (int)sizeof(quint16))
return;
in >> blockSize;
}
qDebug() << "Received DATA II with blocksize " << blockSize;
if (tcpSocket->bytesAvailable() < blockSize)
{
qDebug() << tcpSocket->bytesAvailable() << ' ' << blockSize;
return;
}
qDebug() << "Received DATA III";
in >> data;
qDebug() << data;
QByteArray dbg = data; // create a copy to not alter the buffer itself
dbg.replace('\\', "\\\\"); // escape the backslash itself
dbg.replace('\0', "\\0"); // get rid of 0 characters
dbg.replace('\n', "\\n");
//dbg.replace('"', "\\\""); // more special characters as you like
qDebug() << dbg;
QString data_string(data);
qDebug() << "Emitting Signal";
emit Client::gotData(data_string);
}
void Server::sendData(void)
{
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << (quint16)0;
out << "Hello World, this is a very long text!";
out.device()->seek(0);
out << (quint16)(block.size() - sizeof(quint16));
qDebug() << "First number is: " << (quint16)(block.size() - sizeof(quint16));
qDebug() << "Blocksize is: " << block.size() << "with quint size: " << sizeof(quint16);
qDebug() << "Sending data!";
//Debug
QByteArray dbg = block; // create a copy to not alter the buffer itself
dbg.replace('\\', "\\\\"); // escape the backslash itself
dbg.replace('\0', "\\0"); // get rid of 0 characters
dbg.replace('\n', "\\n");
//dbg.replace('"', "\\\""); // more special characters as you like
qDebug() << dbg;
connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater()));
clientConnection->write(block);
//clientConnection->disconnectFromHost();
}
Connecting works fine, but when I call sendData()
, I get (from the same function) the transmitted block:
First number is: 43
Blocksize is: 45 with quint size: 2
Sending data!
"\0+\0\0\0'Hello World, this is a very long text!\0"
My first problem is: Where do all the \0
come from? As far as I understand the code, first I'm creating a 0
, then I write the text, and them I am going back to the front and write the full size of the block. Is it because of the size of the (quint16)
? When entering nothing, I get \0\0
and a size of 0, which is correct. The size of the example above is 43, which corresponds to +
in ascii (and this sign is in the block above, too).
My second problem is: My readData()
-function does not recognize the block size, (it always returns 450 as block size, which is clearly wrong). Why? Did I miss something?
UPDATE: After changing QByteArray data;
to QString data;
my problems are gone, no more strange \0
in my code -> should have used the right data type -> Head->Desk