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  · 

Q3Socket Class Reference
[Qt3Support module]

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

 #include <Q3Socket>

This class is part of the Qt 3 support library. It is provided to keep old source code working. We strongly advise against using it in new code. See Porting to Qt 4 for more information.

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

Inherits QIODevice.


Public Types

enum Error { ErrConnectionRefused, ErrHostNotFound, ErrSocketRead }
enum State { Idle, HostLookup, Connecting, Connected, Closing }

Public Functions

Q3Socket ( QObject * parent = 0, const char * name = 0 )
virtual ~Q3Socket ()
QHostAddress address () const
Offset at () const
bool at ( Offset index )
void clearPendingData ()
virtual void connectToHost ( const QString & host, Q_UINT16 port )
bool flush ()
int getch ()
bool open ( int m )
QHostAddress peerAddress () const
QString peerName () const
Q_UINT16 peerPort () const
Q_UINT16 port () const
int putch ( int ch )
Q_ULONG readBufferSize () const
void setReadBufferSize ( Q_ULONG bufSize )
virtual void setSocket ( int socket )
virtual void setSocketDevice ( Q3SocketDevice * device )
int socket () const
Q3SocketDevice * socketDevice ()
State state () const
int ungetch ( int ch )
Q_ULONG waitForMore ( int msecs, bool * timeout ) const
Q_ULONG waitForMore ( int msecs ) const

Reimplemented Public Functions

virtual bool atEnd () const
virtual qint64 bytesAvailable () const
virtual qint64 bytesToWrite () const
virtual bool canReadLine () const
virtual void close ()
virtual bool open ( OpenMode m )
virtual Offset size () const
  • 33 public functions inherited from QIODevice
  • 29 public functions inherited from QObject

Signals

void bytesWritten ( int nbytes )
void connected ()
void connectionClosed ()
void delayedCloseFinished ()
void error ( int error )
void hostFound ()
void readyRead ()

Reimplemented Protected Functions

virtual qint64 readData ( char * data, qint64 maxlen )
virtual qint64 writeData ( const char * data, qint64 len )
  • 5 protected functions inherited from QIODevice
  • 7 protected functions inherited from QObject

Additional Inherited Members

  • 1 property inherited from QObject
  • 1 public slot inherited from QObject
  • 5 static public members inherited from QObject
  • 5 protected functions inherited from QIODevice
  • 7 protected functions inherited from QObject

Detailed Description

The Q3Socket 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 Q3Socket 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()). socketDevice() returns a pointer to the Q3SocketDevice used for this socket.

Q3Socket 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.

Warning: Q3Socket is not suitable for use in threads. If you need to uses sockets in threads use the lower-level Q3SocketDevice class.

See also Q3SocketDevice, QHostAddress, and QSocketNotifier.


Member Type Documentation

enum Q3Socket::Error

This enum specifies the possible errors:

ConstantValueDescription
Q3Socket::ErrConnectionRefused0if the connection was refused
Q3Socket::ErrHostNotFound1if the host was not found
Q3Socket::ErrSocketRead2if a read from the socket failed

enum Q3Socket::State

This enum defines the connection states:

ConstantValueDescription
Q3Socket::Idle0if there is no connection
Q3Socket::HostLookup1during a DNS lookup
Q3Socket::Connecting2during TCP connection establishment
Q3Socket::Connected3when there is an operational connection
Q3Socket::Closing4if the socket is closing down, but is not yet closed.


Member Function Documentation

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

Creates a Q3Socket object in Q3Socket::Idle state.

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

Q3Socket::~Q3Socket ()   [virtual]

Destroys the socket. Closes the connection if necessary.

See also close().

QHostAddress Q3Socket::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 Q3Socket::at () const

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

bool Q3Socket::at ( Offset index )

This is an overloaded 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.

bool Q3Socket::atEnd () const   [virtual]

Reimplemented from QIODevice::atEnd().

Returns true if there is no more data to read; otherwise returns false.

qint64 Q3Socket::bytesAvailable () const   [virtual]

Reimplemented from QIODevice::bytesAvailable().

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

See also bytesToWrite().

qint64 Q3Socket::bytesToWrite () const   [virtual]

Reimplemented from QIODevice::bytesToWrite().

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

See also bytesAvailable() and clearPendingData().

void Q3Socket::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 Q3Socket::canReadLine () const   [virtual]

Reimplemented from QIODevice::canReadLine().

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().

void Q3Socket::clearPendingData ()

Deletes the data that is waiting to be written. This is useful if you want to close the socket without waiting for all the data to be written.

See also bytesToWrite(), close(), and delayedCloseFinished().

void Q3Socket::close ()   [virtual]

Reimplemented from QIODevice::close().

Closes the socket.

The read buffer is cleared.

If the output buffer is empty, the state is set to Q3Socket::Idle and the connection is terminated immediately. If the output buffer still contains data to be written, Q3Socket goes into the Q3Socket::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 Q3Socket::Idle and the connection is terminated. At this point, the delayedCloseFinished() signal is emitted.

If you don't want that the data of the output buffer is written, call clearPendingData() before you call close().

See also state(), bytesToWrite(), and clearPendingData().

void Q3Socket::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 Q3Socket 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. Q3Socket will do a normal DNS lookup if required. Note that port is in native byte order, unlike some other libraries.

See also state().

void Q3Socket::connected ()   [signal]

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

See also connectToHost() and connectionClosed().

void Q3Socket::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().

void Q3Socket::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, Q3Socket goes into the Q3Socket::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().

void Q3Socket::error ( int error )   [signal]

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

bool Q3Socket::flush ()

Implementation of the abstract virtual QIODevice::flush() function. This function always returns true.

int Q3Socket::getch ()

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().

void Q3Socket::hostFound ()   [signal]

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

See also connected().

bool Q3Socket::open ( OpenMode m )   [virtual]

Reimplemented from QIODevice::open().

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().

bool Q3Socket::open ( int m )

This is an overloaded function.

QHostAddress Q3Socket::peerAddress () const

Returns the address of the connected peer if the socket is in Connected state; otherwise an empty QHostAddress is returned.

QString Q3Socket::peerName () const

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

Q_UINT16 Q3Socket::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 Q3Socket::port () const

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

int Q3Socket::putch ( int ch )

Writes the character ch to the output buffer.

Returns ch, or -1 if an error occurred.

See also getch().

Q_ULONG Q3Socket::readBufferSize () const

Returns the size of the read buffer.

See also setReadBufferSize().

qint64 Q3Socket::readData ( char * data, qint64 maxlen )   [virtual protected]

Reimplemented from QIODevice::readData().

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

void Q3Socket::readyRead ()   [signal]

This signal is emitted every time there is new incoming data.

Bear in mind that new incoming data is only reported once; if you do not read all the data, this class buffers the data and you can read it later, but no signal is emitted unless new data arrives. A good practice is to read all data in the slot connected to this signal unless you are sure that you need to receive more data to be able to process it.

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

void Q3Socket::setReadBufferSize ( Q_ULONG bufSize )

Sets the size of the Q3Socket's internal read buffer to bufSize.

Usually Q3Socket reads all data that is available from the operating system's socket. If the buffer size is limited to a certain size, this means that the Q3Socket class doesn't buffer more than this size of data.

If the size of the read buffer is 0, the read buffer is unlimited and all incoming data is buffered. This is the default.

If you read the data in the readyRead() signal, you shouldn't use this option since it might slow down your program unnecessary. This option is useful if you only need to read the data at certain points in time, like in a realtime streaming application.

See also readBufferSize().

void Q3Socket::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 Q3Socket class as a wrapper for other socket types (e.g. Unix Domain Sockets).

See also socket().

void Q3Socket::setSocketDevice ( Q3SocketDevice * 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 Q3Socket; after setting the socket call connectToHost() to make the connection.

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

See also socketDevice().

Offset Q3Socket::size () const   [virtual]

Reimplemented from QIODevice::size().

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

int Q3Socket::socket () const

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

See also setSocket().

Q3SocketDevice * Q3Socket::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.

See also setSocketDevice().

State Q3Socket::state () const

Returns the current state of the socket connection.

See also Q3Socket::State.

int Q3Socket::ungetch ( int ch )

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.

Q_ULONG Q3Socket::waitForMore ( int msecs, bool * timeout ) 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.

If timeout is non-null and no error occurred (i.e. it does not return -1): this function sets *timeout to true, if the reason for returning was that the timeout was reached; otherwise it sets *timeout to false. This is useful to find out if the peer closed the connection.

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

See also bytesAvailable().

Q_ULONG Q3Socket::waitForMore ( int msecs ) const

This is an overloaded function.

qint64 Q3Socket::writeData ( const char * data, qint64 len )   [virtual protected]

Reimplemented from QIODevice::writeData().

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

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 94
  2. Apercevoir la troisième dimension ou l'utilisation multithreadée d'OpenGL dans Qt, un article des Qt Quarterly traduit par Guillaume Belz 0
  3. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  4. Pourquoi les programmeurs sont-ils moins payés que les gestionnaires de programmes ? Manquent-ils de pouvoir de négociation ? 42
  5. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  6. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
  7. 2017 : un quinquennat pour une nouvelle version du C++ ? Possible, selon Herb Sutter 8
Page suivante

Le Qt Labs au hasard

Logo

Utiliser OpenCL avec Qt

Les Qt Labs sont les laboratoires des développeurs de Qt, où ils peuvent partager des impressions sur le framework, son utilisation, ce que pourrait être son futur. 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
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