View Full Version : qt socket question

29th August 2006, 15:37
I am still very new to C++/Qt programming. I was hoping that someone could shed some light on something for me:

void Thread::run()
//initalize socket, start connection and detect data available
socket = new QTcpSocket;

if (socket->setSocketDescriptor(sock))
QString welcomeMsg = QString("Welcome to the middleMan\n\n");
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out << (quint16)0;
out << welcomeMsg;
out << (quint16)(block.size() - sizeof(quint16));


while (socket->state() == QAbstractSocket::ConnectedState)

if (socket->bytesAvailable() < 1)
qDebug("Waiting for data...");

if (!socket->waitForReadyRead())

// while (socket->bytesAvailable() > 0)
// {
if (socket->bytesAvailable() > 0)
qDebug("Data available");

QByteArray incomingBlock = socket->readAll();

if (incomingBlock.contains("xml") && !incomingBlock.isEmpty())
dataHandler = new xmlDataHandler;

dataHandler->doParse( &incomingBlock );

char c;


printf("%c", c);
// }

qDebug("Connection closed");

To explain a little bit. This is the run code for a thread that is created and started each time a new connection is requested. I am trying to stream short bits of dynamically created xml like data to the server from a client. I basically want to know when the end of a stream has been reached. How do you figure out the data that is coming across the socket. I assume the beginning of the stream is the header information. Then the data is passed. How do I separate those and only save the data and close the connection after the data is finished streaming? Thanks in advance. Even pointing to a good sockets tutorial would suffice.

29th August 2006, 16:18
out << (quint16)(block.size() - sizeof(quint16));
You don't need this, since QDataStream sends string length too.


I basically want to know when the end of a stream has been reached.
You will never know, unless the other side sends some kind of EOT message. Since you use XML, all you need to know is whether all tags have been closed or not.

29th August 2006, 16:20
There is nothing like "the end of the stream" when talking about TCP sockets. An end of the stream is determined by closing the connection on the transmitter side (for example by using shutdown() function from the BSD socket API).

29th August 2006, 16:28
on the other piece though, how do i decide when the stream starts to flow what is message header info and what is data?

29th August 2006, 16:42
If you are using some kind of protocol (for example HTTP), the protocol should clearly state where does data begin or end. If you implement your own protocol, provide your own means to determine that. If you're using HTTP, you might find using QHttp instead of lower level socket classes convenient.