enum BindFlag {ShareAddress, DontShareAddress, ReuseAddressHint, DefaultForPlatform } flags BindMode QUdpSocket公共函数: QUdpSocket ( QObject * parent = 0 ) virtual ~QUdpSocket () bool bind ( const QHostAddress & address, quint16 port ) bool bind ( const QHostAddress & address, quint16 port, BindMode mode ) bool bind ( quint16 port = 0 ) bool bind ( quint16 port, BindMode mode ) bool hasPendingDatagrams () const bool joinMulticastGroup ( const QHostAddress & groupAddress ) bool joinMulticastGroup ( const QHostAddress & groupAddress, const QNetworkInterface & iface ) bool leaveMulticastGroup ( const QHostAddress & groupAddress ) bool leaveMulticastGroup ( const QHostAddress & groupAddress, const QNetworkInterface & iface ) QNetworkInterface multicastInterface () const qint64 pendingDatagramSize () const qint64 readDatagram ( char * data, qint64 maxSize, QHostAddress * address = 0, quint16 * port = 0 ) void setMulticastInterface ( const QNetworkInterface & iface ) qint64 writeDatagram ( const char * data, qint64 size, const QHostAddress & address, quint16 port ) qint64 writeDatagram ( const QByteArray & datagram, const QHostAddress & host, quint16 port )
Example: void Server::initSocket() { udpSocket = new QUdpSocket(this); udpSocket->bind(QHostAddress::LocalHost, 7755); connect(udpSocket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams())); } void Server::readPendingDatagrams() { while (udpSocket->hasPendingDatagrams()) { QByteArray datagram; datagram.resize(udpSocket->pendingDatagramSize()); QHostAddress sender; quint16 senderPort; udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort); processTheDatagram(datagram); } }
enum QUdpSocket::BindFlag flags QUdpSocket::BindModeBindFlag 这些值可以组成不同的标志,传递给QUdpSocket::bind()函数来修改bind()的特性。
常量定义
|
值
|
描述
|
QUdpSocket::ShareAddress
|
0x1
|
1、允许其他服务绑定同样的地址和端口 2、当多进程通过监听同一地址和端口,进而共享单个服务的负载时,将十分有用(例如:一个拥有几个预先建立的监听者的WEB服务器能够改善响应时间)。不过,由于任何服务都允许重新绑定(rebind),该选项应该引起某些安全上的考虑 3、需要注意的是,把该选项和ReuseAddressHint结合,也会允许你的服务重新绑定一个已存在的共享地址 4、在Unix上,该选项等同于SO_REUSEADDR;在Windows上,该选项被忽略 |
QUdpSocket::DontShareAddress
|
0x2
|
1、采用专有的方式绑定某个地址和端口,其他任何服务都不能再重新绑定
2、通过该选项,确保绑定成功,指定的服务将是地址和端口唯一监听者,就算是拥有ReuseAddressHint的服务也不允许重新绑定
3、在安全性上,该选项优于ShareAddress,但是在某些操作系统上需要管理员的权限才能运行
4、在Unix和Mac OS上,绑定地址和端口的默认行为是非共享,所以该选项会被忽略;在Windows上,等同于SO_EXCLUSIVEADDRUSE套接字选项
|
QUdpSocket::ReuseAddressHint
|
0x4
|
1、为QUdpSocke提供提示,即在地址和端口已经被其他套接字绑定的情况下,也应该试着重新绑定
2、在Unix上,该选项被忽略;在Windows上等同于SO_REUSEADDR
套接字选项
|
QUdpSocket::DefaultForPlatform
|
0x0
|
1、当前平台的默认选项
2、在Unix和Mac OS上,该选项等同于DontShareAddress
+ ReuseAddressHint;在Windows上等同于ShareAddress
|
原文:http://blog.csdn.net/u013686019/article/details/38658433