PDA

View Full Version : [QTcpSocket] disconnectFromHost in a class Destructor



Axtroz
4th June 2011, 16:26
Hello! I'm using QTcpSocket to send messages to a remote server.
Here's a quick example to give you a heads-up:



Myclass::Myclass(QWidget *parent) : QWidget(parent)
{
QTcpSocket *socket = new QTcpSocket; // To know what socket is
// Connect to server and launch session:
socket->connectToHost("server.example.com",12345);
socket->write("Session: self;Start");
// OK, Session is connected.
// If I call this:
socket->write("Session: self; Disconnect");
// The session closes successfully.
}
However...

Myclass::~Myclass() {
socket->write("Session: self; Disconnect");
qDebug() << "Program closing...";
}

On closing my application (Alt+F4, closing the window), the debug console says:
Program closing...
but the socket is not sending the message to the server and my session remains opened.

If I do this:



Myclass::~Myclass()
{
socket->write("Session: this; Disconnect");
QMessageBox::warning(this,"Closing", "Program is closing...");
qDebug() << "Program closed.";
}


And voila, it works. it sends the message, pops up the warning box, and prints the message. Is there a way to make it work without the Messagebox ?

Santosh Reddy
5th June 2011, 23:19
Your QTcpSocket object does not have a parent, and hence will cause a memory leak in you case. You should be doing like this


QTcpSocket *socket = new QTcpSocket(this)

This will ensure that when MyClass is destroyed, QTcpSocket is also properly destroyed.

This should also solve your problem, as when destroying the QTcpSocket, all the pending data is flushed you of the socket and then it is deleted

Axtroz
6th June 2011, 12:10
Thank you, that did solve my problem!

Axtroz
12th June 2011, 14:01
Just to add up, there's one more way to accompish this, one can reimplement QWidget::closeEvent(QCloseEvent*) and use that. Also works and I think it's the better way to do it.