0

I have problem with synchronize(start at the same time QTCPSocket) in my application I have 10 sockets. I have to read data at the similar time to all sockets. At this moment I have something that:

///...///
if(!socket->waitForConnected(-1))
{
    qDebug() << "Server not found";
    emit serverNotFound();

}else if(socket->state()==QAbstractSocket::ConnectedState){
        qDebug() << "Connected"
        connect(timer, SIGNAL(timeout()),this,SLOT(connected())); 
        timer->start(1000);                                                    
    }
}

On connected signal:

void SocketsClass::connected()
{
    sendRequest(socket, messageToServer);
}

The problem is that when the first socket get connected the timer starts for the one.

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
Szymson
  • 990
  • 1
  • 13
  • 28

1 Answers1

1

You can invert your approach. Don't wait for the sockets to get connected. Instead, check if the socket is connected in the slot activated by the timer. In that slot, you can iterate over all sockets and send the message to each of them.

Finally, you should never use Qt's waitForXxx methods, they lead to a horrible pseudo-synchronous code that is very error prone and hard to extend and maintain. Use the signal-slot mechanism instead.

Example:

SocketManager : public QObject {
  Q_OBJECT
  QTcpSocket m_sockets[10];
  QTimer m_timer;
public:
  SocketManager(QObject * parent = 0) : QObject(parent) {
    ... // connect all sockets here
    m_timer.start(1000);
    connect(&m_timer, &QTimer::timeout, [this]{
      for (auto & socket : m_sockets)
        if (socket.state() == QAbstractSocket::ConnectedState)
          sendRequest(socket, messageToServer);
    });
  }
};
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
  • It's working in the way i wanted. The second problem is that i want to insert the value from server to QTableWidget, and I don't know when addRow to QTableWidget because in this case i don't know which socket respond first. – Szymson Jul 28 '15 at 10:21
  • @Szymson Perhaps you should ask another question, then. – Kuba hasn't forgotten Monica Jul 28 '15 at 11:58