QUdpSocket: Cannot receive datagram

泄露秘密 提交于 2019-11-28 05:10:07

问题


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()));
    }
}


来源:https://stackoverflow.com/questions/13773374/qudpsocket-cannot-receive-datagram

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