Using QThread and QtcpServer application crashes
-
I try to make a clients-server application using threads and TcpServer.I know that this issue has been discussed but i don't understand my logical errors.
@
/* The thread's constructor */
FortuneServerThread::FortuneServerThread(int sockDesc,QObject *parent)
: QThread(parent), sockDesc(sockDesc),
{
tcpSocket = new QTcpSocket();
tcpSocket->setSocketDescriptor(sockDesc);
tcpSocket->moveToThread(this);connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readRequest())); connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(discardClient()));
}
/* The running thread's running code */
void FortuneServerThread::run()
{
exec();}
/* This function reads data from Manager and validate it before continue to the next steps /
void FortuneServerThread::readRequest()
{
//read data from packet
QDataStream in(tcpSocket);
bytesread=in.readRawData((char)&client.SOURCE,sizeof(client.SOURCE));// Read data QByteArray data_stream(client.SOURCE.len,QIODevice::ReadOnly); in.readRawData(data_stream.data(), client.SOURCE.items);
....
...
disconnect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readRequest()));tcpSocket->flush(); tcpSocket->close(); tcpSocket->disconnectFromHost();
//
}
@When i try to execute the above code, either the application crashes or if i have an if statement blocks and on debugging displays:QSocketNotifier: Multiple socket notifiers for same socket 1304 and type Read
....
Thanks in Advance! -
-
It seems that you're adding slots to a QThread subclass. That doesn't do what you think. Read http://developer.qt.nokia.com/wiki/Threads_Events_QObjects , especially the 2-3 pitfalls when adding signals/slots to a QThread subclass
-
QDataStream to simply read raw data is nonsense, read directly from the stream. And remember that QDataStream has no means to recovery from short read or writes, therefore isn't supposed to be used as-is on a socket.
-
-
1)I solved the problem with threads:for someone else who has similar problem the solution is:
The connect methods should be in the run method and not to the constructor,because as i understood reading documentation and books,when the thread starts, run method is executing.
@fortuneThread->start();@
2)Thanks peppe,you were right,QDataStream to read raw data was not the best way.