我正在使用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;
}
答案 0 :(得分:2)
我会在绑定之前进行连接。绑定后,readyRead可能会在连接调用完成之前触发。如果您没有清空待处理的数据报,则readyRead将不会再次触发。
答案 1 :(得分:2)
为了将SIGNAL(readyRead())连接到任何槽,QUdpSocket必须位于QAbstractSocket :: BoundState中。虽然在连接之前调用bind,但是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()));
}
}