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  ·  Classes principales  ·  Annotées  ·  Classes groupées  ·  Fonctions  · 

QSocket Class Reference
[network module]

The QSocket class provides a buffered TCP connection. More...

#include <qsocket.h>

Inherits QObject and QIODevice.

List of all member functions.

Public Members

Signals

Protected Slots


Detailed Description

The QSocket class provides a buffered TCP connection.

It provides a totally non-blocking QIODevice, and modifies and extends the API of QIODevice with socket-specific code.

The functions you're likely to call most are connectToHost(), bytesAvailable(), canReadLine() and the ones it inherits from QIODevice.

connectToHost() is the most-used function. As its name implies, it opens a connection to a named host.

Most network protocols are either packet-oriented or line-oriented. canReadLine() indicates whether a connection contains an entire unread line or not, and bytesAvailable() returns the number of bytes available for reading.

The signals error(), connected(), readyRead() and connectionClosed() inform you of the progress of the connection. There are also some less commonly used signals. hostFound() is emitted when connectToHost() has finished its DNS lookup and is starting its TCP connection. delayedCloseFinished() is emitted when close() succeeds. bytesWritten() is emitted when QSocket moves data from its "to be written" queue into the TCP implementation.

There are several access functions for the socket: state() returns whether the object is idle, is doing a DNS lookup, is connecting, has an operational connection, etc. address() and port() return the IP address and port used for the connection. The peerAddress() and peerPort() functions return the IP address and port used by the peer, and peerName() returns the name of the peer (normally the name that was passed to connectToHost()). socket() returns a pointer to the QSocketDevice used for this socket.

QSocket inherits QIODevice, and reimplements some functions. In general, you can treat it as a QIODevice for writing, and mostly also for reading. The match isn't perfect, since the QIODevice API is designed for devices that are controlled by the same machine, and an asynchronous peer-to-peer network connection isn't quite like that. For example, there is nothing that matches QIODevice::size() exactly. The documentation for open(), close(), flush(), size(), at(), atEnd(), readBlock(), writeBlock(), getch(), putch(), ungetch() and readLine() describes the differences in detail.

See also QSocketDevice, QHostAddress, QSocketNotifier and Input/Output and Networking.


Member Type Documentation

QSocket::Error

This enum specifies the possible errors:

  • QSocket::ErrConnectionRefused - if the connection was refused
  • QSocket::ErrHostNotFound - if the host was not found
  • QSocket::ErrSocketRead - if a read from the socket failed

QSocket::State

This enum defines the connection states:

  • QSocket::Idle - if there is no connection
  • QSocket::HostLookup - during a DNS lookup
  • QSocket::Connecting - during TCP connection establishment
  • QSocket::Connected - when there is an operational connection
  • QSocket::Closing - if the socket is closing down, but is not yet closed.

Member Function Documentation

QSocket::QSocket ( QObject * parent = 0, const char * name = 0 )

Creates a QSocket object in QSocket::Idle state.

The parent and name arguments are passed on to the QObject constructor.

QSocket::~QSocket () [virtual]

Destroys the socket. Closes the connection if necessary.

See also close().

QHostAddress QSocket::address () const

Returns the host address of this socket. (This is normally the main IP address of the host, but can be e.g. 127.0.0.1 for connections to localhost.)

Offset QSocket::at () const [virtual]

Returns the current read index. Since QSocket is a sequential device, the current read index is always zero.

Reimplemented from QIODevice.

bool QSocket::at ( Offset index ) [virtual]

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Moves the read index forward to index and returns TRUE if the operation was successful; otherwise returns FALSE. Moving the index forward means skipping incoming data.

Reimplemented from QIODevice.

bool QSocket::atEnd () const [virtual]

Returns TRUE if there is no more data to read; otherwise returns FALSE.

Reimplemented from QIODevice.

Q_ULONG QSocket::bytesAvailable () const

Returns the number of incoming bytes that can be read, i.e. the size of the input buffer. Equivalent to size().

See also bytesToWrite().

Example: network/networkprotocol/nntp.cpp.

Q_ULONG QSocket::bytesToWrite () const

Returns the number of bytes that are waiting to be written, i.e. the size of the output buffer.

See also bytesAvailable().

void QSocket::bytesWritten ( int nbytes ) [signal]

This signal is emitted when data has been written to the network. The nbytes parameter specifies how many bytes were written.

The bytesToWrite() function is often used in the same context; it indicates how many buffered bytes there are left to write.

See also writeBlock() and bytesToWrite().

bool QSocket::canReadLine () const

Returns TRUE if it's possible to read an entire line of text from this socket at this time; otherwise returns FALSE.

Note that if the peer closes the connection unexpectedly, this function returns FALSE. This means that loops such as this won't work:

        while( !socket->canReadLine() ) // WRONG.
            ...
    

See also readLine().

Examples: network/clientserver/client/client.cpp, network/httpd/httpd.cpp, network/mail/smtp.cpp and network/networkprotocol/nntp.cpp.

void QSocket::close () [virtual]

Closes the socket.

The read buffer is cleared.

If the output buffer is empty, the state is set to QSocket::Idle and the connection is terminated immediately. If the output buffer still contains data to be written, QSocket goes into the QSocket::Closing state and the rest of the data will be written. When all of the outgoing data have been written, the state is set to QSocket::Idle and the connection is terminated. At this point, the delayedCloseFinished() signal is emitted.

See also state() and bytesToWrite().

Examples: network/clientserver/client/client.cpp, network/httpd/httpd.cpp and network/networkprotocol/nntp.cpp.

Reimplemented from QIODevice.

void QSocket::connectToHost ( const QString & host, Q_UINT16 port ) [virtual]

Attempts to make a connection to host on the specified port and return immediately.

Any connection or pending connection is closed immediately, and QSocket goes into the HostLookup state. When the lookup succeeds, it emits hostFound(), starts a TCP connection and goes into the Connecting state. Finally, when the connection succeeds, it emits connected() and goes into the Connected state. If there is an error at any point, it emits error().

host may be an IP address in string form, or it may be a DNS name. QSocket will do a normal DNS lookup if required. Note that port is in native byte order, unlike some other libraries.

See also state().

Examples: network/clientserver/client/client.cpp, network/mail/smtp.cpp and network/networkprotocol/nntp.cpp.

void QSocket::connected () [signal]

This signal is emitted after connectToHost() has been called and a connection has been successfully established.

See also connectToHost() and connectionClosed().

Examples: network/clientserver/client/client.cpp, network/mail/smtp.cpp and network/networkprotocol/nntp.cpp.

void QSocket::connectionClosed () [signal]

This signal is emitted when the other end has closed the connection. The read buffers may contain buffered input data which you can read after the connection was closed.

See also connectToHost() and close().

Examples: network/clientserver/client/client.cpp, network/clientserver/server/server.cpp and network/networkprotocol/nntp.cpp.

void QSocket::delayedCloseFinished () [signal]

This signal is emitted when a delayed close is finished.

If you call close() and there is buffered output data to be written, QSocket goes into the QSocket::Closing state and returns immediately. It will then keep writing to the socket until all the data has been written. Then, the delayedCloseFinished() signal is emitted.

See also close().

Examples: network/clientserver/client/client.cpp and network/httpd/httpd.cpp.

void QSocket::error ( int ) [signal]

This signal is emitted after an error occurred. The parameter is the Error value.

Examples: network/clientserver/client/client.cpp and network/networkprotocol/nntp.cpp.

void QSocket::flush () [virtual]

Implementation of the abstract virtual QIODevice::flush() function.

Reimplemented from QIODevice.

int QSocket::getch () [virtual]

Reads a single byte/character from the internal read buffer. Returns the byte/character read, or -1 if there is nothing to be read.

See also bytesAvailable() and putch().

Reimplemented from QIODevice.

void QSocket::hostFound () [signal]

This signal is emitted after connectToHost() has been called and the host lookup has succeeded.

See also connected().

Example: network/networkprotocol/nntp.cpp.

bool QSocket::open ( int m ) [virtual]

Opens the socket using the specified QIODevice file mode m. This function is called automatically when needed and you should not call it yourself.

See also close().

Reimplemented from QIODevice.

QHostAddress QSocket::peerAddress () const

Returns the host address as resolved from the name specified to the connectToHost() function.

QString QSocket::peerName () const

Returns the host name as specified to the connectToHost() function. An empty string is returned if none has been set.

Example: network/mail/smtp.cpp.

Q_UINT16 QSocket::peerPort () const

Returns the peer's host port number, normally as specified to the connectToHost() function. If none has been set, this function returns 0.

Note that Qt always uses native byte order, i.e. 67 is 67 in Qt; there is no need to call htons().

Q_UINT16 QSocket::port () const

Returns the host port number of this socket, in native byte order.

int QSocket::putch ( int ch ) [virtual]

Writes the character ch to the output buffer.

Returns ch, or -1 if an error occurred.

See also getch().

Reimplemented from QIODevice.

Q_LONG QSocket::readBlock ( char * data, Q_ULONG maxlen ) [virtual]

Reads maxlen bytes from the socket into data and returns the number of bytes read. Returns -1 if an error occurred.

Example: network/networkprotocol/nntp.cpp.

Reimplemented from QIODevice.

QString QSocket::readLine () [virtual]

Returns a line of text including a terminating newline character (\n). Returns "" if canReadLine() returns FALSE.

See also canReadLine().

Examples: network/clientserver/client/client.cpp, network/httpd/httpd.cpp, network/mail/smtp.cpp and network/networkprotocol/nntp.cpp.

void QSocket::readyRead () [signal]

This signal is emitted when there is incoming data to be read.

This signal is emitted every time there is new incoming data. Bear in mind that new incoming data is only reported once; i.e. if you do not read all the data when you get this signal you may lose data if more data is received in the meantime.

See also readBlock(), readLine() and bytesAvailable().

Examples: network/clientserver/client/client.cpp, network/httpd/httpd.cpp, network/mail/smtp.cpp and network/networkprotocol/nntp.cpp.

void QSocket::setSocket ( int socket ) [virtual]

Sets the socket to use socket and the state() to Connected. The socket must already be connected.

This allows us to use the QSocket class as a wrapper for other socket types (e.g. Unix Domain Sockets).

Example: network/httpd/httpd.cpp.

void QSocket::setSocketDevice ( QSocketDevice * device ) [virtual]

Sets the internal socket device to device. Passing a device of 0 will cause the internal socket device to be used. Any existing connection will be disconnected before using the new device.

The new device should not be connected before being associated with a QSocket; after setting the socket call connectToHost() to make the connection.

This function is useful if you need to subclass QSocketDevice and want to use the QSocket API, for example, to implement Unix domain sockets.

Offset QSocket::size () const [virtual]

Returns the number of incoming bytes that can be read right now (like bytesAvailable()).

Reimplemented from QIODevice.

void QSocket::sn_read ( bool force = FALSE ) [virtual protected slot]

Internal slot for handling socket read notifications.

This function has can usually only be entered once (i.e. no recursive calls). If the argument force is TRUE, the function is executed, but no readyRead() signals are emitted. This behaviour is useful for the waitForMore() function, so that it is possible to call waitForMore() in a slot connected to the readyRead() signal.

void QSocket::sn_write () [virtual protected slot]

Internal slot for handling socket write notifications.

int QSocket::socket () const

Returns the socket number, or -1 if there is no socket at the moment.

QSocketDevice * QSocket::socketDevice ()

Returns a pointer to the internal socket device.

There is normally no need to manipulate the socket device directly since this class does the necessary setup for most applications.

State QSocket::state () const

Returns the current state of the socket connection.

See also QSocket::State.

Examples: network/clientserver/client/client.cpp and network/networkprotocol/nntp.cpp.

int QSocket::ungetch ( int ch ) [virtual]

This implementation of the virtual function QIODevice::ungetch() prepends the character ch to the read buffer so that the next read returns this character as the first character of the output.

Reimplemented from QIODevice.

Q_ULONG QSocket::waitForMore ( int msecs ) const

Wait up to msecs milliseconds for more data to be available.

If msecs is -1 the call will block indefinitely.

Returns the number of bytes available.

Warning: This is a blocking call and should be avoided in event driven applications.

See also bytesAvailable().

Q_LONG QSocket::writeBlock ( const char * data, Q_ULONG len ) [virtual]

Writes len bytes to the socket from data and returns the number of bytes written. Returns -1 if an error occurred.

Example: network/networkprotocol/nntp.cpp.

Reimplemented from QIODevice.


This file is part of the Qt toolkit. Copyright © 1995-2002 Trolltech. All Rights Reserved.

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 ? 94
  4. Les développeurs détestent-ils les antivirus ? Un programmeur manifeste sa haine envers ces solutions de sécurité 32
  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 Quarterly au hasard

Logo

Le tri des QListView

Qt Quarterly est la revue trimestrielle proposée par Nokia et à destination des développeurs Qt. Ces articles d'une grande qualité technique sont rédigés par des experts Qt. 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 3.0
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