3

我正在使用 QUdpSocket 来接收来自服务器的数据。当我使用 SFML 接收数据时,我可以通过 SocketUdp 接收数据,但使用 qt 它不起作用。

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;
}
4

2 回答 2

2

我会在绑定之前进行连接。绑定之后,readyRead 可能会在连接调用完成之前触发。如果您不清空待处理的数据报,readyRead 将不会再次触发。

于 2012-12-08T01:51:01.037 回答
2

为了将 SIGNAL(readyRead()) 连接到任何插槽,QUdpSocket 必须位于 QAbstractSocket::BoundState 中。尽管您在连接之前调用了绑定,但 QUdpSocket 上的绑定会进行非阻塞调用,这意味着绑定可能会延迟。为确保在绑定完成且 QUdpSocket 处于绑定状态后将 SIGNAL(readyRead()) 连接到 SLOT(QtReceive()),请执行以下操作:

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()));
    }
}
于 2013-11-24T15:48:06.567 回答