Results 1 to 6 of 6

Thread: problem with Tcp socket reception in a thread...

  1. #1
    Join Date
    Sep 2010
    Posts
    10
    Thanks
    4
    Qt products
    Qt4 Qt/Embedded
    Platforms
    Windows

    Default problem with Tcp socket reception in a thread...

    Hello every one,

    I am really grateful for such a wonderful support forum for QT. I could get most of my question answered till today except this one... Great going...

    the basic functionality:
    create a gui application and then create a thread that holds a tcpsocket connection and perform a tedious calculation on the data received on the Socket..

    the tcp connection at which the data is received is LocalHost:3000


    I created a basic QT GUI application and then at the press of a button; i would create a thread with the command...
    Qt Code:
    1. mythread *txt = new mythread();
    2. txt->start();
    To copy to clipboard, switch view to plain text mode 

    the thread is defined with the following constructor...
    mythread.h


    Qt Code:
    1. class mythread : public QThread
    2. {
    3. Q_OBJECT
    4. public:
    5. mythread(QObject *parent = 0);
    6. void run();
    7. private :
    8. QTcpSocket socket;
    9. }
    To copy to clipboard, switch view to plain text mode 



    mythread.cpp



    Qt Code:
    1. mythread::mythread(QObject *parent)
    2. : QThread(parent)
    3. {
    4. }
    5.  
    6. void mythread::run(){
    7.  
    8. qint64 maxlen = 128;
    9. socket.connectToHost(QHostAddress::LocalHost,3000);
    10. if (socket.waitForConnected(1000))
    11. qDebug("Connected!");
    12. char buffer[128];
    13. //QDataStream in(&socket);
    14. //in.setVersion(QDataStream::Qt_4_6);
    15. while(1){
    16. qint64 len = socket.readLine(buffer, maxlen);
    17.  
    18. if(len < 0){
    19. qDebug()<<"the break function";
    20. break;
    21. }
    22. qDebug()<<"The buffer is" <<buffer<<"and its size is "<<len;
    23. }
    24. }
    To copy to clipboard, switch view to plain text mode 



    After i run this, i always get the error saying that


    QObject: Cannot create children for a parent that is in a different thread. (Parent is QTcpSocket(0x980df60), parent's thread is QThread(0x3d4ec8), current thread is mythread(0x980df58)
    QObject: Cannot create children for a parent that is in a different thread.
    (Parent is QTcpSocket(0x980df60), parent's thread is QThread(0x3d4ec8), current thread is mythread(0x980df58)
    Connected!
    The buffer is and its size is 0
    The buffer is and its size is 0
    The buffer is and its size is 0
    The buffer is and its size is 0
    The buffer is and its size is 0
    The buffer is and its size is 0
    The buffer is and its size is 0
    The buffer is and its size is 0
    The buffer is and its size is 0
    The buffer is and its size is 0



    Could any one help me in this regard...

    Thanking you

    Rajesh Medampudi....

  2. #2
    Join Date
    Jan 2006
    Location
    Warsaw, Poland
    Posts
    33,359
    Thanks
    3
    Thanked 5,015 Times in 4,792 Posts
    Qt products
    Qt3 Qt4 Qt5 Qt/Embedded
    Platforms
    Unix/X11 Windows Android Maemo/MeeGo
    Wiki edits
    10

    Default Re: problem with Tcp socket reception in a thread...

    In general the problem is mythread object lives in the context of the main thread and not the thread it represents. So your socket object will be created in the context of the main thread and you should handle it there. I think that in your case everything you have to do is to get rid of the socket member variable and create the socket instance in the run() method.

    Qt Code:
    1. void mythread::run() {
    2. QTcpSocket socket;
    3. qint64 maxlen = 128;
    4. socket.connectToHost(QHostAddress::LocalHost,3000);
    5. if (socket.waitForConnected(1000))
    6. qDebug("Connected!");
    7. else { ... }
    8. char buffer[128];
    9.  
    10. while(1){
    11. // you should wait for data here!
    12. socket.waitForReadyRead();
    13. // and make sure there is a whole line to read!
    14. if(!socket.canReadLine()) continue;
    15. qint64 len = socket.readLine(buffer, maxlen);
    16. if(len < 0){
    17. qDebug()<<"the break function";
    18. break;
    19. }
    20. qDebug()<<"The buffer is" <<buffer<<"and its size is "<<len;
    21. }
    22. }
    To copy to clipboard, switch view to plain text mode 
    I also corrected your code a bit but I don't guarantee it will work.
    Your biological and technological distinctiveness will be added to our own. Resistance is futile.

    Please ask Qt related questions on the forum and not using private messages or visitor messages.


  3. The following user says thank you to wysota for this useful post:

    medampudi (9th September 2010)

  4. #3
    Join Date
    Sep 2009
    Location
    UK
    Posts
    2,447
    Thanks
    6
    Thanked 348 Times in 333 Posts
    Qt products
    Qt4
    Platforms
    Windows

    Default Re: problem with Tcp socket reception in a thread...

    Why use TCP socket reception in a thread? Do it in your main UI threead, and then spawn off the tedious calculation into a seperate thread and use signals to signify the finish of the calculation (or use QtConcurrent or similar).

  5. The following user says thank you to squidge for this useful post:

    medampudi (9th September 2010)

  6. #4
    Join Date
    Sep 2010
    Posts
    10
    Thanks
    4
    Qt products
    Qt4 Qt/Embedded
    Platforms
    Windows

    Default Re: problem with Tcp socket reception in a thread...

    thank you very much @wysota - the program works like a charm... might be that i needed some commands to wait and accept the TCP values.Thank you very much... Any how My first foray into Threads and TCP works now...

    @squidge.. The program needs to use the same thread and store teh values of past variables too and using a concurrent programming did not meet my needs of having a threaded simple interface.. And i think you are right that i could just call this from the main UI and hence eliminate the intermediate Thread but the problem being portability and no. of changes in the original source code of the Tedious Function...(It inherits a lot of other custom defined base classes that are not native QT kind) hence to reduce my work, I just used a Thread to work it out all together.. the thread uses the signals and slots along with the main UI class for signaling events.

    I also wanted to use this experience of threads as a learning ground for the other part of the application of communicating with the robots...

    Thank you Once Again Both of you.... for your inputs on this program...

  7. #5
    Join Date
    Feb 2013
    Posts
    1
    Qt products
    Qt4
    Platforms
    Unix/X11 Windows

    Default Re: problem with Tcp socket reception in a thread...

    Hi! I have quite similar problem with Qthread.

    Everything is ok until I unlink the Ethernet cable. And Try reconnect when connection error signel recived.


    from console:
    socket: QObject(0x0)
    socket: QTcpSocket(0xafb02498)
    Connecting to: "192.168.1.5"
    resize event
    "Ppm2_window" OGOLNY
    show event
    MODEL:x: false
    "Ppm2_window" OGOLNY
    console request
    permision to send data: true
    Socket state: QAbstractSocket::HostLookupState
    Socket state: QAbstractSocket::ConnectingState
    Not connected: true
    sock open: false
    Socket state: QAbstractSocket::UnconnectedState
    sock open: false
    Socket error: "Unknown error"
    Socket error: QAbstractSocket::SocketTimeoutError

    Connecting to: "192.168.1.5"
    Socket state: QAbstractSocket::HostLookupState
    Socket state: QAbstractSocket::ConnectingState
    QObject: Cannot create children for a parent that is in a different thread.
    (Parent is QTcpSocket(0xafb02498), parent's thread is TcpClient(0x8473da0), current thread is QThread(0x82f66a8)
    QObject: Cannot create children for a parent that is in a different thread.
    (Parent is QTcpSocket(0xafb02498), parent's thread is TcpClient(0x8473da0), current thread is QThread(0x82f66a8)
    Socket state: QAbstractSocket::UnconnectedState
    sock open: true
    Socket error: "Host unreachable"
    Socket error: QAbstractSocket::NetworkError
    Network error: "Host unreachable"
    Not connected: true
    sock open: false
    Socket state: QAbstractSocket::UnconnectedState
    sock open: false
    My Qestion is. Why it works like that? I have no idea how to solve this problem

    Qt Code:
    1. #ifndef TCPCLIENT_H
    2. #define TCPCLIENT_H
    3.  
    4. #include <QThread>
    5. #include <QTcpSocket>
    6. #include <QAbstractSocket>
    7. #include <QObject>
    8. #include <QDebug>
    9. #include <QTime>
    10. #include "globalne.h"
    11.  
    12. class TcpClient : public QThread
    13. {
    14. Q_OBJECT
    15.  
    16.  
    17.  
    18. public:
    19.  
    20. explicit TcpClient(QObject *parent = 0);
    21. ~TcpClient();
    22. void run();
    23. bool StartConnection();
    24. void zakoncz_polaczenie_z_e1000();
    25.  
    26. signals:
    27. void dataReady(QByteArray, QTime);
    28. void connectionError();
    29.  
    30. public slots:
    31. void readyRead();
    32. void disconnected();
    33. void connected();
    34. void stateChanged(QAbstractSocket::SocketState);
    35. void displayError(QAbstractSocket::SocketError);
    36. // void bytesWritten (qint64 bytes);
    37.  
    38.  
    39. private:
    40.  
    41. // CanMon canmnon_parent;
    42. // QTcpSocket socket;
    43. QTcpSocket *socket;
    44. QTime time;
    45. // QStringList lista;
    46. bool ponawiaj;
    47.  
    48.  
    49.  
    50. };
    51.  
    52. #endif // TCPCLIENT_H
    To copy to clipboard, switch view to plain text mode 



    Qt Code:
    1. //#include "tcpclient.h"
    2.  
    3. //TcpClient::TcpClient(QObject *parent) :
    4. // QObject(parent)
    5. //{
    6. //}
    7.  
    8. #include <QStringList>
    9. #include "tcpclient.h"
    10.  
    11. #include <QFile>
    12. #include <QTextStream>
    13.  
    14.  
    15. TcpClient::TcpClient(QObject *parent) :
    16. QThread(parent)
    17. {
    18.  
    19. socket = NULL;
    20. qRegisterMetaType<QAbstractSocket::SocketError>("QAbstractSocket::SocketError");
    21. qRegisterMetaType<QAbstractSocket::SocketState>("QAbstractSocket::SocketState");
    22. ponawiaj = true;
    23.  
    24. }
    25.  
    26. TcpClient::~TcpClient()
    27. {
    28. // qDebug() << "p";
    29.  
    30.  
    31. disconnect(socket,SIGNAL(connected()), this, SLOT(connected()));
    32. disconnect(socket,SIGNAL(readyRead()),this,SLOT(readyRead()));
    33. disconnect(socket,SIGNAL(disconnected()), this, SLOT(disconnected()));
    34. // disconnect(socket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),this,SLOT(stateChanged(qSockState)));
    35. socket->close();
    36. qDebug() << "socket open: " << socket->isOpen();
    37. delete socket;
    38. }
    39.  
    40. void TcpClient::stateChanged(QAbstractSocket::SocketState st)
    41. {
    42. qDebug() << "Socket state: " << st;
    43. switch(st)
    44. {
    45. case QAbstractSocket::UnconnectedState:
    46. qDebug() << "sock open: " << socket->isOpen();
    47. break;
    48. }
    49. }
    50.  
    51. void TcpClient::displayError(QAbstractSocket::SocketError se)
    52. {
    53. qDebug() << "Socket error: " << socket->errorString();
    54. qDebug() << "Socket error: " << se;
    55.  
    56. switch(se)
    57. {
    58. case QAbstractSocket::SocketTimeoutError:
    59. StartConnection();
    60. break;
    61. case QAbstractSocket::NetworkError:
    62. qDebug() << "Network error: " << socket->errorString();
    63. break;
    64.  
    65. }
    66.  
    67. // this->StartConnection();
    68. }
    69.  
    70. bool TcpClient::StartConnection()
    71. {
    72. #define z_pliku 0
    73.  
    74. #if z_pliku
    75. QFile mFile("iphosta.cfg");
    76. if (!mFile.open(QFile::ReadOnly | QFile::Text))
    77. {
    78. qDebug() << mFile.errorString();
    79. qDebug() << "nie otworzono pliku... próba połączenia z localhost";
    80. socket->connectToHost("localhost",4010);
    81. }
    82. else
    83. {
    84. QTextStream in(&mFile);
    85. QString host = in.readAll();
    86. mFile.close();
    87. qDebug() << "Connecting to: " << host;
    88. socket->connectToHost(host,4010);
    89. }
    90. #else
    91. QString host = "192.168.1.5";
    92. // QString host = "192.168.1.48";
    93. qDebug() << "Connecting to: " << host;
    94.  
    95. socket->connectToHost(host,4010);
    96. #endif
    97.  
    98. if(socket->waitForConnected(5000))
    99. {
    100. qDebug() << "Connected: " << socket->isOpen();
    101.  
    102. }
    103. else
    104. {
    105. qDebug() << "Not connected: " << socket->isOpen();
    106. socket->close();
    107. }
    108.  
    109. qDebug() << "sock open: " << socket->isOpen();
    110.  
    111. return socket->isOpen();
    112. }
    113.  
    114. void TcpClient::zakoncz_polaczenie_z_e1000()
    115. {
    116. int result;
    117. if (socket->state())
    118. {
    119. result = socket->write(QByteArray::fromHex(QString("e1fc00000000000000000000000000000000000000000000000000f7e000e2").toAscii()));
    120. qDebug() << "nadano koniec polaczenia: " << result;
    121. this->msleep(500);
    122. qDebug() << "minely 2 sekundy";
    123. }
    124. ponawiaj = false;
    125. }
    126.  
    127. void TcpClient::run()
    128. {
    129. qDebug() << "socket: " << socket;
    130. if(!socket)
    131. socket = new QTcpSocket();
    132. qDebug() << "socket: " << socket;
    133.  
    134. connect(socket,SIGNAL(connected()), this, SLOT(connected()));
    135. connect(socket,SIGNAL(readyRead()),this,SLOT(readyRead()));
    136. connect(socket,SIGNAL(disconnected()), this, SLOT(disconnected()));
    137. connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),this, SLOT(displayError(QAbstractSocket::SocketError)));
    138. connect(socket,SIGNAL( stateChanged(QAbstractSocket::SocketState)),this, SLOT(stateChanged(QAbstractSocket::SocketState)));
    139. // error(QAbstractSocket::SocketError)
    140. // SIGNAL(stateChanged(qSockState)),this,SLOT(tcStateChanged(qSockState)));
    141.  
    142. this->StartConnection();
    143. this->exec();
    144.  
    145. }
    146.  
    147. void TcpClient::connected()
    148. {
    149. qDebug() << "connection established: " << socket->isOpen();
    150. }
    151.  
    152. void TcpClient::disconnected()
    153. {
    154. qDebug() << " Disconnected";
    155. }
    156.  
    157. void TcpClient::readyRead()
    158. {
    159.  
    160. QByteArray data;
    161.  
    162. // qDebug() << "Redy read ";
    163.  
    164. if (socket->bytesAvailable() > 0)
    165. {
    166. // qDebug() << "dostepne bajty: " << socket->bytesAvailable();
    167.  
    168. data = socket->readAll();
    169. // qDebug() << "odebrano: " << data.toHex();
    170. time.start();
    171. // qDebug() << "TIME: " << time.toString() << "." << time.msec();
    172. emit dataReady(data, time);
    173. }
    174. }
    To copy to clipboard, switch view to plain text mode 

  8. #6
    Join Date
    Jan 2006
    Location
    Graz, Austria
    Posts
    8,416
    Thanks
    37
    Thanked 1,544 Times in 1,494 Posts
    Qt products
    Qt3 Qt4 Qt5
    Platforms
    Unix/X11 Windows

    Default Re: problem with Tcp socket reception in a thread...

    That looks weird quite wrong. All your slots are being executed in the main thread (cross thread signal/slot connections, receiver object "thsi" belongs to main thread).

    Cheers,
    _

Similar Threads

  1. Socket + thread problem
    By Daxos in forum Qt Programming
    Replies: 11
    Last Post: 13th July 2010, 11:28
  2. socket & thread
    By prashant in forum Qt Programming
    Replies: 2
    Last Post: 2nd December 2009, 10:09
  3. thread with socket?
    By triperzonak in forum Qt Programming
    Replies: 6
    Last Post: 25th September 2008, 16:21
  4. Socket on a Thread
    By ^NyAw^ in forum Qt Programming
    Replies: 2
    Last Post: 7th May 2008, 15:56
  5. Thread, Timer and Socket. Comuication problem
    By ^NyAw^ in forum Qt Programming
    Replies: 6
    Last Post: 17th January 2008, 16:48

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.