Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Toutes les fonctions  ·  Vues d'ensemble  · 

QUdpSocket Class Reference
[QtNetwork module]

The QUdpSocket class provides a UDP socket. More...

 #include <QUdpSocket>

This class is not part of the Qt GUI Framework Edition.

Inherits QAbstractSocket.

Note: All functions in this class are reentrant.


Public Types

enum BindFlag { ShareAddress, DontShareAddress, ReuseAddressHint, DefaultForPlatform }
flags BindMode

Public Functions

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
qint64 pendingDatagramSize () const
qint64 readDatagram ( char * data, qint64 maxSize, QHostAddress * address = 0, quint16 * port = 0 )
qint64 writeDatagram ( const char * data, qint64 size, const QHostAddress & address, quint16 port )
qint64 writeDatagram ( const QByteArray & datagram, const QHostAddress & host, quint16 port )

Additional Inherited Members


Detailed Description

The QUdpSocket class provides a UDP socket.

UDP (User Datagram Protocol) is a lightweight, unreliable, datagram-oriented, connectionless protocol. It can be used when reliability isn't important. QUdpSocket is a subclass of QAbstractSocket that allows you to send and receive UDP datagrams.

The most common way to use this class is to bind to an address and port using bind(), then call writeDatagram() and readDatagram() to transfer data. If you want to use the standard QIODevice functions read(), readLine(), write(), etc., you must first connect the socket directly to a peer by calling connectToHost().

The socket emits the bytesWritten() signal every time a datagram is written to the network. If you just want to send datagrams, you don't need to call bind().

The readyRead() signal is emitted whenever datagrams arrive. In that case, hasPendingDatagrams() returns true. Call pendingDatagramSize() to obtain the size of the first pending datagram, and readDatagram() to read it.

Note: An incoming datagram should be read when you receive the readyRead() signal, otherwise this signal will not be emitted for the next datagram.

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);
     }
 }

With QUdpSocket, you can also establish a virtual connection to a UDP server using connectToHost() and then use read() and write() to exchange datagrams without specifying the receiver for each datagram.

The Broadcast Sender and Broadcast Receiver examples illustrate how to use QUdpSocket in applications.

Symbian Platform Security Requirements

On Symbian, processes which use this class must have the NetworkServices platform security capability. If the client process lacks this capability, operations will result in a panic.

Platform security capabilities are added via the TARGET.CAPABILITY qmake variable.

See also QTcpSocket.


Member Type Documentation

enum QUdpSocket::BindFlag
flags QUdpSocket::BindMode

This enum describes the different flags you can pass to modify the behavior of QUdpSocket::bind().

Note: On Symbian OS bind flags behaviour depends on process capabilties. If process has NetworkControl capability, the bind attempt with ReuseAddressHint will always succeed even if the address and port is already bound by another socket with any flags. If process does not have NetworkControl capability, the bind attempt to address and port already bound by another socket will always fail.

ConstantValueDescription
QUdpSocket::ShareAddress0x1Allow other services to bind to the same address and port. This is useful when multiple processes share the load of a single service by listening to the same address and port (e.g., a web server with several pre-forked listeners can greatly improve response time). However, because any service is allowed to rebind, this option is subject to certain security considerations. Note that by combining this option with ReuseAddressHint, you will also allow your service to rebind an existing shared address. On Unix, this is equivalent to the SO_REUSEADDR socket option. On Windows, this option is ignored.
QUdpSocket::DontShareAddress0x2Bind the address and port exclusively, so that no other services are allowed to rebind. By passing this option to QUdpSocket::bind(), you are guaranteed that on successs, your service is the only one that listens to the address and port. No services are allowed to rebind, even if they pass ReuseAddressHint. This option provides more security than ShareAddress, but on certain operating systems, it requires you to run the server with administrator privileges. On Unix and Mac OS X, not sharing is the default behavior for binding an address and port, so this option is ignored. On Windows, this option uses the SO_EXCLUSIVEADDRUSE socket option.
QUdpSocket::ReuseAddressHint0x4Provides a hint to QUdpSocket that it should try to rebind the service even if the address and port are already bound by another socket. On Windows, this is equivalent to the SO_REUSEADDR socket option. On Unix, this option is ignored.
QUdpSocket::DefaultForPlatform0x0The default option for the current platform. On Unix and Mac OS X, this is equivalent to (DontShareAddress + ReuseAddressHint), and on Windows, its equivalent to ShareAddress.

This enum was introduced in Qt 4.1.

The BindMode type is a typedef for QFlags<BindFlag>. It stores an OR combination of BindFlag values.


Member Function Documentation

QUdpSocket::QUdpSocket ( QObject * parent = 0 )

Creates a QUdpSocket object.

parent is passed to the QObject constructor.

See also socketType().

QUdpSocket::~QUdpSocket ()   [virtual]

Destroys the socket, closing the connection if necessary.

See also close().

bool QUdpSocket::bind ( const QHostAddress & address, quint16 port )

Binds this socket to the address address and the port port. When bound, the signal readyRead() is emitted whenever a UDP datagram arrives on the specified address and port. This function is useful to write UDP servers.

On success, the functions returns true and the socket enters BoundState; otherwise it returns false.

The socket is bound using the DefaultForPlatform BindMode.

See also readDatagram().

bool QUdpSocket::bind ( const QHostAddress & address, quint16 port, BindMode mode )

This is an overloaded function.

Binds to address on port port, using the BindMode mode.

This function was introduced in Qt 4.1.

bool QUdpSocket::bind ( quint16 port = 0 )

This is an overloaded function.

Binds to QHostAddress:Any on port port.

bool QUdpSocket::bind ( quint16 port, BindMode mode )

This is an overloaded function.

Binds to QHostAddress:Any on port port, using the BindMode mode.

This function was introduced in Qt 4.1.

bool QUdpSocket::hasPendingDatagrams () const

Returns true if at least one datagram is waiting to be read; otherwise returns false.

See also pendingDatagramSize() and readDatagram().

qint64 QUdpSocket::pendingDatagramSize () const

Returns the size of the first pending UDP datagram. If there is no datagram available, this function returns -1.

See also hasPendingDatagrams() and readDatagram().

qint64 QUdpSocket::readDatagram ( char * data, qint64 maxSize, QHostAddress * address = 0, quint16 * port = 0 )

Receives a datagram no larger than maxSize bytes and stores it in data. The sender's host address and port is stored in *address and *port (unless the pointers are 0).

Returns the size of the datagram on success; otherwise returns -1.

If maxSize is too small, the rest of the datagram will be lost. To avoid loss of data, call pendingDatagramSize() to determine the size of the pending datagram before attempting to read it. If maxSize is 0, the datagram will be discarded.

See also writeDatagram(), hasPendingDatagrams(), and pendingDatagramSize().

qint64 QUdpSocket::writeDatagram ( const char * data, qint64 size, const QHostAddress & address, quint16 port )

Sends the datagram at data of size size to the host address address at port port. Returns the number of bytes sent on success; otherwise returns -1.

Datagrams are always written as one block. The maximum size of a datagram is highly platform-dependent, but can be as low as 8192 bytes. If the datagram is too large, this function will return -1 and error() will return DatagramTooLargeError.

Sending datagrams larger than 512 bytes is in general disadvised, as even if they are sent successfully, they are likely to be fragmented by the IP layer before arriving at their final destination.

Warning: In S60 5.0 and earlier versions, the writeDatagram return value is not reliable for large datagrams.

Warning: Calling this function on a connected UDP socket may result in an error and no packet being sent. If you are using a connected socket, use write() to send datagrams.

See also readDatagram() and write().

qint64 QUdpSocket::writeDatagram ( const QByteArray & datagram, const QHostAddress & host, quint16 port )

This is an overloaded function.

Sends the datagram datagram to the host address host and at port port.

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 103
  2. Pourquoi les programmeurs sont-ils moins payés que les gestionnaires de programmes ? Manquent-ils de pouvoir de négociation ? 56
  3. «Le projet de loi des droits du développeur» : quelles conditions doivent remplir les entreprises pour que le développeur puisse réussir ? 90
  4. Les développeurs détestent-ils les antivirus ? Un programmeur manifeste sa haine envers ces solutions de sécurité 31
  5. Qt Commercial : Digia organise un webinar gratuit le 27 mars sur la conception d'interfaces utilisateur et d'applications avec le framework 0
  6. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  7. 2017 : un quinquennat pour une nouvelle version du C++ ? Possible, selon Herb Sutter 11
Page suivante
  1. Linus Torvalds : le "C++ est un langage horrible", en justifiant le choix du C pour le système de gestion de version Git 100
  2. Comment prendre en compte l'utilisateur dans vos applications ? Pour un développeur, « 90 % des utilisateurs sont des idiots » 231
  3. Quel est LE livre que tout développeur doit lire absolument ? Celui qui vous a le plus marqué et inspiré 96
  4. Apple cède et s'engage à payer des droits à Nokia, le conflit des brevets entre les deux firmes s'achève 158
  5. Nokia porte à nouveau plainte contre Apple pour violation de sept nouveaux brevets 158
  6. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 103
  7. Quel est le code dont vous êtes le plus fier ? Pourquoi l'avez-vous écrit ? Et pourquoi vous a-t-il donné autant de satisfaction ? 83
Page suivante

Le Qt Developer Network au hasard

Logo

Comment fermer une application

Le Qt Developer Network est un réseau de développeurs Qt anglophone, où ils peuvent partager leur expérience sur le framework. Lire l'article.

Communauté

Ressources

Liens utiles

Contact

  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

Qt dans le magazine

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt 4.6-snapshot
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !
 
 
 
 
Partenaires

Hébergement Web