udp的广播,多播,单播 demo
enum class EMsgType:uint8_t
{
EMSGT_SINGLE,//单播
EMSGT_MULTICAST,//多播
EMSGT_BROADCAST,//广播
};
sendSocket =new QUdpSocket(this);
sendSocket->setSocketOption(QAbstractSocket::MulticastTtlOption, 1);
sendSocket->bind(QHostAddress::AnyIPv4, 0,QUdpSocket::ShareAddress|QUdpSocket::ReuseAddressHint);
void MainWindow::SendUdpData(const QByteArray &SendData, const QHostAddress &ip, quint16 port, EMsgType msgType)
{
cout<<"ip: “<<ip<<”, port: "<<port;
//广播
if(msgType == EMsgType::EMSGT_BROADCAST)
{
cout<<“EMsgType::EMSGT_BROADCAST:”<writeDatagram(SendData,QHostAddress::Broadcast,port);
}
else if(msgType == EMsgType::EMSGT_MULTICAST)
{
//多播
sendSocket->joinMulticastGroup(QHostAddress(ip));
cout<<“EMsgType::EMSGT_MULTICAST:”<writeDatagram(SendData,QHostAddress(ip),port);
}
else
{
//单播
sendSocket->leaveMulticastGroup(QHostAddress(ip));
cout<<“EMsgType::EMSGT_SINGLE:”<writeDatagram(SendData,QHostAddress(ip),port);
}
}