Eneboo - Documentación para desarrolladores
Tipos públicos | Señales | Métodos públicos | Slots protegidos
Referencia de la Clase QSocket

The QSocket class provides a buffered TCP connection.network. Más...

#include <qsocket.h>

Diagrama de herencias de QSocket
QObject QIODevice QObject QIODevice Qt Qt Qt Qt

Lista de todos los miembros.

Tipos públicos

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

Señales

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

Métodos públicos

 QSocket (QObject *parent=0, const char *name=0)
virtual ~QSocket ()
State state () const
int socket () const
virtual void setSocket (int)
QSocketDevicesocketDevice ()
virtual void setSocketDevice (QSocketDevice *)
virtual void connectToHost (const QString &host, Q_UINT16 port)
QString peerName () const
bool open (int mode)
void close ()
void flush ()
Offset size () const
Offset at () const
bool at (Offset)
bool atEnd () const
Q_ULONG bytesAvailable () const
Q_ULONG waitForMore (int msecs, bool *timeout) const
Q_ULONG waitForMore (int msecs) const
Q_ULONG bytesToWrite () const
void clearPendingData ()
Q_LONG readBlock (char *data, Q_ULONG maxlen)
Q_LONG writeBlock (const char *data, Q_ULONG len)
Q_LONG readLine (char *data, Q_ULONG maxlen)
int getch ()
int putch (int)
int ungetch (int)
bool canReadLine () const
virtual QString readLine ()
Q_UINT16 port () const
Q_UINT16 peerPort () const
QHostAddress address () const
QHostAddress peerAddress () const
void setReadBufferSize (Q_ULONG)
Q_ULONG readBufferSize () const
 QSocket (QObject *parent=0, const char *name=0)
virtual ~QSocket ()
State state () const
int socket () const
virtual void setSocket (int)
QSocketDevicesocketDevice ()
virtual void setSocketDevice (QSocketDevice *)
virtual void connectToHost (const QString &host, Q_UINT16 port)
QString peerName () const
bool open (int mode)
void close ()
void flush ()
Offset size () const
Offset at () const
bool at (Offset)
bool atEnd () const
Q_ULONG bytesAvailable () const
Q_ULONG waitForMore (int msecs, bool *timeout) const
Q_ULONG waitForMore (int msecs) const
Q_ULONG bytesToWrite () const
void clearPendingData ()
Q_LONG readBlock (char *data, Q_ULONG maxlen)
Q_LONG writeBlock (const char *data, Q_ULONG len)
Q_LONG readLine (char *data, Q_ULONG maxlen)
int getch ()
int putch (int)
int ungetch (int)
bool canReadLine () const
virtual QString readLine ()
Q_UINT16 port () const
Q_UINT16 peerPort () const
QHostAddress address () const
QHostAddress peerAddress () const
void setReadBufferSize (Q_ULONG)
Q_ULONG readBufferSize () const

Slots protegidos

virtual void sn_read (bool force=FALSE)
virtual void sn_write ()
virtual void sn_read (bool force=FALSE)
virtual void sn_write ()

Descripción detallada

The QSocket class provides a buffered TCP connection.

network.

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

Note that a QApplication must have been constructed before this class can be used.

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

Atención:
QSocket is not suitable for use in threads. If you need to uses sockets in threads use the lower-level QSocketDevice class.
Because Qt doesn't use the native socketstream implementation on Mac OS X, QSocket has an implicit transfer latency of 100ms. You can achieve lower latency on Mac OS X by using QSocketDevice instead.
Ver también:
QSocketDevice, QHostAddress, QSocketNotifier

Documentación de las enumeraciones miembro de la clase

This enum specifies the possible errors: ErrConnectionRefused if the connection was refused ErrHostNotFound if the host was not found ErrSocketRead if a read from the socket failed

Valores de enumeraciones:
ErrConnectionRefused 
ErrHostNotFound 
ErrSocketRead 
ErrConnectionRefused 
ErrHostNotFound 
ErrSocketRead 
Valores de enumeraciones:
ErrConnectionRefused 
ErrHostNotFound 
ErrSocketRead 
ErrConnectionRefused 
ErrHostNotFound 
ErrSocketRead 
Valores de enumeraciones:
Idle 
HostLookup 
Connecting 
Connected 
Closing 
Connection 
Idle 
HostLookup 
Connecting 
Connected 
Closing 
Connection 

This enum defines the connection states:

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

Valores de enumeraciones:
Idle 
HostLookup 
Connecting 
Connected 
Closing 
Connection 
Idle 
HostLookup 
Connecting 
Connected 
Closing 
Connection 

Documentación del constructor y destructor

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.

Note that a QApplication must have been constructed before sockets can be used.

QSocket::~QSocket ( ) [virtual]

Destroys the socket. Closes the connection if necessary.

Ver también:
close()
QSocket::QSocket ( QObject parent = 0,
const char *  name = 0 
)
virtual QSocket::~QSocket ( ) [virtual]

Documentación de las funciones miembro

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

QHostAddress QSocket::address ( ) const
QIODevice::Offset QSocket::at ( ) const [virtual]

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

Reimplementado de QIODevice.

Offset QSocket::at ( ) const [virtual]

Virtual function that returns the current I/O device position.

This is the position of the data read/write head of the I/O device.

Ver también:
size()

Reimplementado de QIODevice.

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

Virtual function that sets the I/O device position to pos. Returns TRUE if the position was successfully set, i.e. pos is within range and the seek was successful; otherwise returns FALSE.

Ver también:
size()

Reimplementado de QIODevice.

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

Esta es una función miembro sobrecargada que se suministra por conveniencia. Difiere de la anterior función solamente en los argumentos que acepta. 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.

Reimplementado de QIODevice.

bool QSocket::atEnd ( ) const [virtual]

Virtual function that returns TRUE if the I/O device position is at the end of the input; otherwise returns FALSE.

Reimplementado de QIODevice.

bool QSocket::atEnd ( ) const [virtual]

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

Reimplementado de QIODevice.

Q_ULONG QSocket::bytesAvailable ( ) const
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().

This function can trigger the readyRead() signal, if more data has arrived on the socket.

Ver también:
bytesToWrite()
Q_ULONG QSocket::bytesToWrite ( ) const

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

Ver también:
bytesAvailable() clearPendingData()
Q_ULONG QSocket::bytesToWrite ( ) const
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.

Ver también:
writeBlock(), bytesToWrite()
void QSocket::bytesWritten ( int  nbytes) [signal]
bool QSocket::canReadLine ( ) const
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
            ;
Ver también:
readLine()
void QSocket::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.

Ver también:
bytesToWrite() close() delayedCloseFinished()
void QSocket::clearPendingData ( )
void QSocket::close ( void  ) [virtual]

Closes the I/O device.

This virtual function must be reimplemented by all subclasses.

Ver también:
open()

Implementa QIODevice.

void QSocket::close ( void  ) [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.

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

Ver también:
state(), bytesToWrite() clearPendingData()

Implementa QIODevice.

void QSocket::connected ( ) [signal]

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

Ver también:
connectToHost(), connectionClosed()
void QSocket::connected ( ) [signal]
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.

Ver también:
connectToHost(), close()
void QSocket::connectionClosed ( ) [signal]
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.

Ver también:
state()
virtual void QSocket::connectToHost ( const QString host,
Q_UINT16  port 
) [virtual]
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.

Ver también:
close()
void QSocket::delayedCloseFinished ( ) [signal]
void QSocket::error ( int  t0) [signal]

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

void QSocket::error ( int  ) [signal]
void QSocket::flush ( ) [virtual]

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

Implementa QIODevice.

void QSocket::flush ( ) [virtual]

Flushes an open I/O device.

This virtual function must be reimplemented by all subclasses.

Implementa QIODevice.

int QSocket::getch ( ) [virtual]

Reads a single byte/character from the I/O device.

Returns the byte/character read, or -1 if the end of the I/O device has been reached.

This virtual function must be reimplemented by all subclasses.

Ver también:
putch(), ungetch()

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

Ver también:
bytesAvailable(), putch()

Implementa QIODevice.

void QSocket::hostFound ( ) [signal]

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

Ver también:
connected()
void QSocket::hostFound ( ) [signal]
bool QSocket::open ( int  mode) [virtual]

Opens the I/O device using the specified mode. Returns TRUE if the device was successfully opened; otherwise returns FALSE.

The mode parameter mode must be an OR'ed combination of the following flags. Mode flags Meaning IO_Raw specifies raw (unbuffered) file access. IO_ReadOnly opens a file in read-only mode. IO_WriteOnly opens a file in write-only mode. IO_ReadWrite opens a file in read/write mode. IO_Append sets the file index to the end of the file. IO_Truncate truncates the file. IO_Translate enables carriage returns and linefeed translation for text files under MS-DOS, Windows and Macintosh. On Unix systems this flag has no effect. Use with caution as it will also transform every linefeed written to the file into a CRLF pair. This is likely to corrupt your file if you write write binary data. Cannot be combined with IO_Raw.

This virtual function must be reimplemented by all subclasses.

Ver también:
close()

Implementa QIODevice.

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.

Ver también:
close()

Implementa QIODevice.

QHostAddress QSocket::peerAddress ( ) const
QHostAddress QSocket::peerAddress ( ) const

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

QString QSocket::peerName ( ) const
QString QSocket::peerName ( ) const

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

Q_UINT16 QSocket::peerPort ( ) const
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
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 I/O device.

Returns ch, or -1 if an error occurred.

This virtual function must be reimplemented by all subclasses.

Ver también:
getch(), ungetch()

Implementa QIODevice.

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

Writes the character ch to the output buffer.

Returns ch, or -1 if an error occurred.

Ver también:
getch()

Implementa QIODevice.

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

Reads at most maxlen bytes from the I/O device into data and returns the number of bytes actually read.

This function should return -1 if a fatal error occurs and should return 0 if there are no bytes to read.

The device must be opened for reading, and data must not be 0.

This virtual function must be reimplemented by all subclasses.

Ver también:
writeBlock() isOpen() isReadable()

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

Implementa QIODevice.

Q_ULONG QSocket::readBufferSize ( ) const
Q_ULONG QSocket::readBufferSize ( ) const

Returns the size of the read buffer.

Ver también:
setReadBufferSize()
Q_LONG QSocket::readLine ( char *  data,
Q_ULONG  maxlen 
) [virtual]

Reads a line of text, (or up to maxlen bytes if a newline isn't encountered) plus a terminating '\0' into data. If there is a newline at the end if the line, it is not stripped.

Returns the number of bytes read including the terminating '\0', or -1 if an error occurred.

This virtual function can be reimplemented much more efficiently by the most subclasses.

Ver también:
readBlock(), QTextStream::readLine()

Reimplementado de QIODevice.

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

Reimplementado de QIODevice.

QString QSocket::readLine ( ) [virtual]

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

Ver también:
canReadLine()
void QSocket::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.

Ver también:
readBlock(), readLine(), bytesAvailable()
void QSocket::readyRead ( ) [signal]
void QSocket::setReadBufferSize ( Q_ULONG  bufSize)

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

Usually QSocket 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 QSocket 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.

Ver también:
readBufferSize()
void QSocket::setReadBufferSize ( Q_ULONG  )
virtual void QSocket::setSocket ( int  ) [virtual]
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).

virtual void QSocket::setSocketDevice ( QSocketDevice ) [virtual]
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.

QIODevice::Offset QSocket::size ( ) const [virtual]

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

Implementa QIODevice.

Offset QSocket::size ( ) const [virtual]

Virtual function that returns the size of the I/O device.

Ver también:
at()

Implementa QIODevice.

virtual void QSocket::sn_read ( bool  force = FALSE) [protected, virtual, slot]
void QSocket::sn_read ( bool  force = FALSE) [protected, virtual, slot]
void QSocket::sn_write ( ) [protected, virtual, slot]
virtual void QSocket::sn_write ( ) [protected, virtual, slot]
int QSocket::socket ( ) const
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.

QSocketDevice* QSocket::socketDevice ( )
State QSocket::state ( ) const

Returns bits OR'ed together that specify the current state.

The flags are: IO_Open.

Subclasses may define additional flags.

Reimplementado de QIODevice.

QSocket::State QSocket::state ( ) const

Returns the current state of the socket connection.

Ver también:
QSocket::State

Reimplementado de QIODevice.

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.

Implementa QIODevice.

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

Puts the character ch back into the I/O device and decrements the index position if it is not zero.

This function is normally called to "undo" a getch() operation.

Returns ch, or -1 if an error occurred.

This virtual function must be reimplemented by all subclasses.

Ver también:
getch(), putch()

Implementa QIODevice.

Q_ULONG QSocket::waitForMore ( int  msecs) const

Esta es una función miembro sobrecargada que se suministra por conveniencia. Difiere de la anterior función solamente en los argumentos que acepta.

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

Atención:
This is a blocking call and should be avoided in event driven applications.
Ver también:
bytesAvailable()
Q_LONG QSocket::writeBlock ( const char *  data,
Q_ULONG  len 
) [virtual]

Writes len bytes from data to the I/O device and returns the number of bytes actually written.

This function should return -1 if a fatal error occurs.

This virtual function must be reimplemented by all subclasses.

Ver también:
readBlock()

Implementa QIODevice.

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.

Implementa QIODevice.


La documentación para esta clase fue generada a partir de los siguientes ficheros:
 Todo Clases Namespaces Archivos Funciones Variables 'typedefs' Enumeraciones Valores de enumeraciones Propiedades Amigas 'defines'