0

I'm on Linux with QT 4.8.

I would like that 2 or more processes on the same machine could listen on the same port for UDP datagrams. Qt documentation says that QUdpSocket::ShareAddress can do that.

I have implemented 2 receivers with this code:

connect(&rec, SIGNAL(readyRead()), this, SLOT(leggiDati()));
rec.bind(QHostAddress::any, 5000, QUdpSocket::ShareAddress);

the "leggiDati()" function:

while(rec.hasPendingDatagrams()){
  QByteArray dato;
  dato.resize(rec.pendingDatagramSize());
  rec.readDatagram(dato.data(), dato.size(), &sender, & port);
}

and the sender code:

QUdpSocket send;
QByteArray dato = "prova invio";
send.writeDatagram(dato.data(), dato.size(), QHostAddress::LocalHost, 5000);

With the previous code, only the last process started receives the datagram. if I send a broadcast datagram, instead of on localhost, both processes receive the message.

can anyone explain to me why this happens? Is there any way to permit communications on localhost avoiding to send broadcast messages?

4

1 回答 1

1

这归结为了解套接字如何绑定到端口。所以你正在经历预期的行为。

两个应用程序可以监听同一个端口吗?

关于多播 UDP,我从来没有想出正确的套接字选项来允许它与 QtNetwork 模块一起工作。如果我真的需要为这个功能坚持使用 Qt,我会创建自己的套接字并使用 setSocketDescriptor()。但相反,我通常求助于ACE C++ 库来获取与多播UDP 相关的任何内容。

于 2013-06-17T20:52:39.373 回答