PDA

View Full Version : Unable to read from QTcpSocket



jimroos
4th July 2007, 20:17
I'm trying to read a TCP stream sent from a third party TCP server. I've create a thread that is able to connect to the server succesfully but is unable to read any of the data being transmitted. I've tried to determine if I've got data using the readyRead signal and by periodically checking the bytesAvailable() method.

I have disable my systems firewall programs. I have also been able to receive the data from the third party server using the TCPBuilder TCP testing utility and using windows hyperterminal.

Here is a code snippet. Any help would be greatly appreciated.

void TCPClientServer::run()
{
this->m_bolThreadIsRunning = true;

this->m_bolRunning = this->initClientTcp();

while(this->m_bolRunning)
{
if(!this->m_ptrTcpSocket->isOpen())
{
this->m_ptrTcpSocket->connectToHost(this->m_strIpAddress,
this->m_intPortNumber, QIODevice::ReadWrite);
if(!this->m_ptrTcpSocket->waitForConnected(3000))
{
this->m_ptrTcpSocket->close();
}
}
else if(this->m_ptrTcpSocket->bytesAvailable() > 0)
{
emit this->sendSocketState("Valid Socket");
}

// Go to sleep for 1 second
this->msleep(500);
}
this->m_ptrTcpSocket->close();
if(this->m_ptrTcpSocket != (QTcpSocket*)NULL)
delete this->m_ptrTcpSocket;

if(this->m_ptrDataStream != (QDataStream*)NULL)
delete this->m_ptrDataStream;

this->m_bolThreadIsRunning = false;
}

bool TCPClientServer::initClientTcp()
{
// Create the socket
this->m_ptrTcpSocket = new QTcpSocket;

// Setup the signals and slots
connect(m_ptrTcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this,
SLOT(socketError(QAbstractSocket::SocketError)), Qt:directConnection);
connect(m_ptrTcpSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)) ,
this, SLOT(slotSocketState(QAbstractSocket::SocketState) ),Qt:directConnection);
connect(m_ptrTcpSocket, SIGNAL(readyRead()), this, SLOT(slotReady()),
Qt:directConnection);

this->m_ptrDataStream = new QDataStream(this->m_ptrTcpSocket);

return(true);
}

jacek
4th July 2007, 21:09
If you want to use the asynchronous QTcpSocket interface, get rid of that while loop and msleep() and invoke QThread::exec() to start the event loop. Otherwise you have to invoke waitForReadyRead() to allow the socket to receive data.