I'm trying to write a multithreaded chat program based on the threaded fortune server example.
The setup:
My first step was to prevent the thread from terminating immediately, a while loop in the Thread::run() method, as shown below, did this nicely...or so i thought.
void Thread::closeConnectionNow()
{
socket->disconnectFromHost();
socket->waitForDisconnect(1);
}
void Thread::closeConnection()
{
socket->deleteLater();
}
void Thread::readData()
{
//code for reading data
}
void Thread::run()
{
...
connect(socket, SIGNAL(readyRead()), this, SLOT(readData()));
connect(socket, SIGNAL(disconnected()), this, SLOT(closeConnection()));
socket->waitForDisconnected(-1);
}
void Thread::closeConnectionNow()
{
socket->disconnectFromHost();
socket->waitForDisconnect(1);
}
void Thread::closeConnection()
{
socket->deleteLater();
}
void Thread::readData()
{
//code for reading data
}
void Thread::run()
{
...
connect(socket, SIGNAL(readyRead()), this, SLOT(readData()));
connect(socket, SIGNAL(disconnected()), this, SLOT(closeConnection()));
while (socket->state() == QAbstractSocket::ConnectedState)
socket->waitForDisconnected(-1);
}
To copy to clipboard, switch view to plain text mode
note: The closeConnectionNow()-method is available to the thread's parent.
What works:
The thread runs, and waits in the loop while still answering readyRead() signals properly. When the client closes the connection, the disconnected() signal is received correctly and the thread exits.
What doesn't work:
Calling the closeConnectionNow()-method from the parent thread does not have any effect. It executes but the socket refuses to close.
Have i missed some critical step that would allow the thread to close the connection?
Perhaps the solution i've chosen is flawed to begin with and i should find a single-threaded solution instead?
Any input is appreciated! Thanks in advance!
Bookmarks