QT using multiple threads to read and write data problems encountered QTcpSocket

Multithreading used The QTcpSocket
new new The QTcpSocket the run () method; then monitor the readyRead () signal connect (m_pTcpSocket, SIGNAL (readyRead ( )), this, SLOT (sloat_RecvData ()));

The problem is when you need to send some command to the server (using m_pTcpSocket-> write (byteArray);) the program will report the warning QSocketNotifier: not socket notifiers CAN BE Another Enabled from the Thread .
I have to connect to a TCP server and send data to the server using QTcpSocket in QThread subclass WorkerThread in.
the WorkerThread :: RUN void ()
{
  m_pTcpSocket The QTcpSocket new new = ();
  the while (. 1) {
    ...;
    m_pTcpSocket-> the connectToHost (QHostAddress :: LocalHost, 8001);  // connection server
    m_pTcpSocket-> waitForConnected (3000);              // wait successful connection
    int nByteWrite m_pTcpSocket- => Write (strMessage.toUtf8 ());                 // send data to the server 
  }
}
Can connect to the server, but when you call write transmit data, the server has not receive shows here sending fails, the client unable to pronounce the data -
to solve :
Later, after using the write () method after, re-use flush () method, a message can be sent.
Official documents of qt says, calling the flush () method after, the buffered data can be sent at once.
The estimated QTcpSocket write () method is having buffered.
the WorkerThread :: RUN void ()
{
  m_pTcpSocket The QTcpSocket new new = ();
  the while (. 1) {
    ...;
    m_pTcpSocket-> the connectToHost (QHostAddress :: LocalHost, 8001);
    m_pTcpSocket-> waitForConnected (3000);
    int nByteWrite m_pTcpSocket- => Write (strMessage.toUtf8 ()); m_pTcpSocket-> the flush ();   } }
    

上面的客户端TcpSocket成功地将数据write发送给了服务端,但是又发现客户端readyRead信号一直不进它的槽函数sloat_RecvData()。真是一波刚平一波又起啊,现在客户端又收不到数据了~
解决
检查connect(tcpSocket, SIGNAL(readyRead()),this,SLOT(update_message()));返回值为true,说明信号槽连接起来了~
服务端检查write函数的返回值,为非零,说明也发出去了~
线程while(1)循环很快,在该循环中,循环过快,导致connect来不及处理数据,所以使用waitForReadyRead()将循环进行阻塞,当有数据读入时取消阻塞,进入下一轮循环。
void WorkerThread::run()
{
  m_pTcpSocket = new QTcpSocket();
  while (1) {
    …;
    m_pTcpSocket->connectToHost(QHostAddress::LocalHost, 8001);
    m_pTcpSocket->waitForConnected(3000);
    int nByteWrite = m_pTcpSocket->write(strMessage.toUtf8());
    m_pTcpSocket->flush();
    m_pSocket->waitForReadyRead();
  }
}

在多线程中是socket,确实挺棘手的!记录一下,仅供参考~

Guess you like

Origin www.cnblogs.com/MakeView660/p/10938075.html