刚实现的跨平台Qt的网络邻居之TCP加网络编程中的广播实现,有需要的同学看看吧。
最原始的版本,目前正在改进的。不过够大家学习和日常使用的了。
部分代码如下:
tcp数据发送和接收在压缩包里面哦。
//发送广播数据
void PeerManager::sendBroadcastData()
{
// qDebug()<<__FUNCTION__;
QByteArray datagram(username);
datagram.append('@');
datagram.append(QByteArray::number(mServerPort));
bool validBroadcastAddress = true;
/*foreach( QHostAddress address,broadcastAddrs )*/{
if( broadcastSocket.writeDatagram(datagram,QHostAddress::Broadcast,broadcastPort) == -1 ){
validBroadcastAddress = false;
}
// qDebug()<< __FUNCTION__ <<datagram.constData();
}
if(!validBroadcastAddress )
{
updateAddress();
}
//读取广播数据
void PeerManager::readBroadcastData()
{
if( !mCloseState )
return;
while ( broadcastSocket.hasPendingDatagrams() ){
QHostAddress senderIp;
quint16 senderPort;
QByteArray datagram;
datagram.resize(broadcastSocket.pendingDatagramSize());
if( broadcastSocket.readDatagram(datagram.data(),datagram.size(),&senderIp,&senderPort) == -1)
{
continue;
}
// qDebug()<<__FUNCTION__<<datagram.constData();
// qDebug()<<__FUNCTION__<<senderIp.toString();
QList<QByteArray> list = datagram.split('@');
if( list.size() != 2 )
{
continue;
}
int senderServerPort = list.at(1).toInt();
if( isLocalHostAddress(senderIp))
{
continue;
}
if( !peerHash.contains(senderIp))
{
peerHash.insert(senderIp,senderServerPort);
}
else
{
peerHash[senderIp] = senderServerPort;
}
emit sigNewNeighBor(senderIp,senderServerPort);
}
}
---------------------
作者:新潮开发
来源:CSDN
原文:https://blog.csdn.net/poolooloo/article/details/89919273
版权声明:本文为博主原创文章,转载请附上博文链接!
网友评论