QUdpSocket: Cannot receive datagram

2019-02-18 22:44发布

问题:

I am using QUdpSocket in order to receive data from a server. When i receive data With SFML its working, i can receive data throught SocketUdp but with qt it doesn't work.

void TheClass::Bind()
{
  m_sock_receive = new QUdpSocket(this);
  if (m_sock_receive->bind(QHostAddress::Any, port))
  {
    std::cout << "Bind: OK" << std::endl;
    connect(m_sock_receive, SIGNAL(readyRead()), this, SLOT(QtReceive()));
  } 
  else
      std::cout << "Bind: NOK" << std::endl;
}

void TheClass::QtReceive()
{
    std::cout << "Pending data !" << std::endl;
}

回答1:

I would make the connect before the bind. It's possible that after binding, the readyRead fires before the connect call is completed. If you don't empty the pending datagrams, the readyRead will not fire again.



回答2:

In order to connect SIGNAL(readyRead()) to any slot, the QUdpSocket must be in a QAbstractSocket::BoundState. Although you call bind before connect, the bind on QUdpSocket makes a non-blocking call, meaning, that the bind might be delayed. To ensure that you connect the SIGNAL(readyRead()) to SLOT(QtReceive()) after the bind has finished and the QUdpSocket is in a bound state, do the following:

void TheClass::Bind()
{
  m_sock_receive = new QUdpSocket(this);
  connect(m_sock_receive, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
        this, SLOT(onSocketStateChange(QAbstractSocket::SocketState)));
  if (m_sock_receive->bind(QHostAddress::Any, port))
  {
    std::cout << "Bind: OK" << std::endl;
  } 
  else
      std::cout << "Bind: NOK" << std::endl;
}

void TheClass::QtReceive()
{
    std::cout << "Pending data !" << std::endl;
}

void TheClass::onSocketStateChange (QAbstractSocket::SocketState state) {
    if ( state == QAbstractSocket::BoundState ) {
        connect(m_sock_receive, SIGNAL(readyRead()), this, SLOT(QtReceive()));
    }
}