QUdpSocket: Cannot receive datagram

旧街凉风 提交于 2019-11-29 11:30:17

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.

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()));
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!