When I have a QThread which is responsible for handling a connection for a client application, I seem to have a strange problem. When I allocate a QTcpSocket in the constructor of the QThread, I do not succeed to open a connection afterwards in run(). When I do the allocation in run(), no problems arises. Any idea what might cause this ?

Header file :

Qt Code:
  1. #ifndef CONNECTIONTHREAD_H
  2. #define CONNECTIONTHREAD_H
  3.  
  4. #include <QThread>
  5. #include <QString>
  6.  
  7. class QTcpSocket;
  8.  
  9. class ConnectionThread : public QThread
  10. {
  11. Q_OBJECT
  12.  
  13. public:
  14. ConnectionThread(QObject *parent);
  15. ~ConnectionThread();
  16.  
  17. bool isConnected() const;
  18.  
  19. signals:
  20. void connectionEstablished();
  21.  
  22. public slots:
  23. //void setHostInfo(QString& hostName, int portNumber);
  24.  
  25. private:
  26. void run();
  27.  
  28. QTcpSocket* tcpSocket_;
  29. bool connected_;
  30. QString hostName_;
  31. int portNumber_;
  32.  
  33. };
  34.  
  35. #endif // CONNECTIONTHREAD_H
To copy to clipboard, switch view to plain text mode 

This works :

Qt Code:
  1. #include "connectionthread.h"
  2. #include <QTcpSocket>
  3.  
  4. ConnectionThread::ConnectionThread(QObject *parent)
  5. : QThread(parent)
  6. {
  7. connected_ = false;
  8.  
  9. hostName_ = "localhost";
  10. portNumber_ = 4974;
  11.  
  12. connect(this, SIGNAL(connectionEstablished()), parent, SLOT(connectionEstablished()));
  13. }
  14.  
  15. ConnectionThread::~ConnectionThread()
  16. {
  17. }
  18.  
  19. bool ConnectionThread::isConnected() const
  20. {
  21. return connected_;
  22. }
  23.  
  24. void ConnectionThread::run()
  25. {
  26. tcpSocket_ = new QTcpSocket(this);
  27.  
  28. tcpSocket_->abort();
  29. tcpSocket_->connectToHost(hostName_, portNumber_);
  30.  
  31. if (tcpSocket_->waitForConnected(1000))
  32. emit connectionEstablished();
  33.  
  34. exec();
  35. }
To copy to clipboard, switch view to plain text mode 


This does not :

Qt Code:
  1. #include "connectionthread.h"
  2. #include <QTcpSocket>
  3.  
  4. ConnectionThread::ConnectionThread(QObject *parent)
  5. : QThread(parent)
  6. {
  7. connected_ = false;
  8.  
  9. tcpSocket_ = new QTcpSocket(this);
  10.  
  11. hostName_ = "localhost";
  12. portNumber_ = 4974;
  13.  
  14. connect(this, SIGNAL(connectionEstablished()), parent, SLOT(connectionEstablished()));
  15. }
  16.  
  17. ConnectionThread::~ConnectionThread()
  18. {
  19. }
  20.  
  21. bool ConnectionThread::isConnected() const
  22. {
  23. return connected_;
  24. }
  25.  
  26. void ConnectionThread::run()
  27. {
  28. tcpSocket_->abort();
  29. tcpSocket_->connectToHost(hostName_, portNumber_);
  30.  
  31. if (tcpSocket_->waitForConnected(1000))
  32. emit connectionEstablished();
  33.  
  34. exec();
  35. }
To copy to clipboard, switch view to plain text mode