c++ - QUdpSocket - 数据报被接收两次,为什么?
问题描述
我在我的 QUdpSocket 上收到了两次数据报,即使我正在看 wireshark 并且它只收到一次。我创建了套接字并在端口 11112 上侦听。还有另一个设备在我正在侦听的此端口上发出数据。对于发送的每条实际消息,我始终收到两条消息。我不确定是什么原因造成的。有什么想法吗?
精简代码:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_socket = new QUdpSocket(this);
connect (m_socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(onSocketStateChange(QAbstractSocket::SocketState)));
m_socket->bind(11112, QUdpSocket::ShareAddress);
}
MainWindow::~MainWindow()
{
delete ui;
delete m_socket;
}
void MainWindow::readPendingDatagrams()
{
QByteArray buffer;
QHostAddress sender;
quint16 port;
while(m_socket->hasPendingDatagrams())
{
int s = m_socket->pendingDatagramSize();
buffer.resize(s);
//for some reason there are two datagrams on the line.
// I have verified with wireshark that there is only one from the
// sender so not sure what is happening under the hood...
m_socket->readDatagram(buffer.data(),buffer.size(),&sender, &port);
QString source = sender.toString().split(":")[3];
if (source == "172.20.23.86")
{
qInfo() << buffer <<endl;
}
}
}
void MainWindow::onSocketStateChange(QAbstractSocket::SocketState state)
{
if ( state == QAbstractSocket::BoundState ) {
connect(m_socket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));
}
}
解决方案
如果数据报被发送到广播地址,并且您绑定到所有接口 (0.0.0.0),并且接收数据报的接口有两个,则可能会发生这种情况。要排除这种可能性,请切换到receiveDatagram
API 并转储您收到的数据报的全部详细信息。我敢打赌,您收到它的界面每次都会有所不同。
您还readPendingDatagrams
可能多次连接插槽,因此它可能会被多次触发,尽管hasPendingDatagrams
应该false
第二次返回 - 所以虽然这可能不是问题,但这是您必须解决的问题。它应该只连接一次 - 当您构造套接字时,即在构造函数中。
推荐阅读
- node.js - 在 node.js 中创建 Firebase 存储访问令牌
- assembly - 32 位编译器程序集 nasm 中两个 64 位定点数的乘法
- excel - 在活动的 Excel 文档中使用 VBA 从 powershell 连接到 Excel
- sql - 如何根据分组的 A 列获取 B 列的值
- firebase - Firebase Cloud Function 只能由另一个函数触发
- ios - 快速启动屏幕动画后更改为另一个视图控制器
- php - 无法在动态链接库 xampp/php/ext/php_imagic.dll 中定位程序入口点 add_index_zval
- python - 如何键入注释字符串的长度?
- javascript - 用 HTML 的输入替换了 JS 中的固定变量
- reactjs - event.target.value 显示未定义