main.cpp#include <QApplication>#include <QDebug>//#include "tcpserver.h"//int main(int argc, char **argv){ QApplication app(argc, argv); TcpServer server; return app.exec();}
tcpserver.h#ifndef TCPSERVER_H#define TCPSERVER_H//#include <QTcpServer>#include <QTimer>//#include "serverconnection.h"//class TcpServer : public QObject{Q_OBJECTpublic: TcpServer(QObject *parent = 0); ~TcpServer();private slots: void incomingConnection();protected: QTcpServer *tcpServer; ServerConnection *conn;};#endif
tcpserver.cpp#include "tcpserver.h"//TcpServer::TcpServer( QObject *parent ) : QObject(parent){ qDebug() << "TcpServer::TcpServer()"; setObjectName("TcpServer"); tcpServer = new QTcpServer(this); tcpServer->setObjectName("QTcpServer"); connect(tcpServer, SIGNAL(newConnection()), SLOT(incomingConnection())); tcpServer->listen(QHostAddress::Any, (quint16)5406); }TcpServer::~TcpServer(){ qDebug() << "TcpServer::~TcpServer()"; delete tcpServer;}void TcpServer::incomingConnection(){ qDebug() << "TcpServer::incomingConnection()"; conn = new ServerConnection(tcpServer->nextPendingConnection(), this->tcpServer); connect(conn, SIGNAL(finished()), conn, SLOT(deleteLater())); dumpObjectTree();}
serverconnection.h#ifndef SERVERCONNECTION_H#define SERVERCONNECTION_H//#include <QThread>#include <QtNetwork>//class ServerConnection : public QThread{Q_OBJECTpublic: ServerConnection(QTcpSocket *socket, QObject *parent = 0); ~ServerConnection(); void run(); signals: void receiveDataFromClient(QHostAddress host);private slots: void receiveData(); private: QTcpSocket *m_pTcpSocket; quint8 m_startByte; quint8 m_blockSize; };#endif
serverconnection.cpp//#include "serverconnection.h"//ServerConnection::ServerConnection( QTcpSocket *socket, QObject *parent) : QThread(parent), m_pTcpSocket(socket){ qDebug() << "ServerConnection::ServerConnection()"; setObjectName(QString("ServerConnection%1").arg(socket->peerPort())); m_pTcpSocket->setParent(this); m_pTcpSocket->setObjectName(QString("Socket%1").arg(socket->peerPort())); connect(m_pTcpSocket, SIGNAL(disconnected()), SLOT(quit())); connect(m_pTcpSocket, SIGNAL(readyRead()),SLOT(receiveData())); dumpObjectTree(); start();}ServerConnection::~ServerConnection(){ qDebug() << "ServerConnection::~ServerConnection()"; delete m_pTcpSocket;}void ServerConnection::run(){ qDebug() << "ServerConnection::run()"; exec();}void ServerConnection::receiveData(){// действия}
connect(conn, SIGNAL(finished()), conn, SLOT(deleteLater()));
Note that entering and leaving a new event loop (e.g., by opening a modal dialog) will not perform the deferred deletion; for the object to be deleted, the control must return to the event loop from which deleteLater() was called.
See also destroyed() and QPointer.