Qt:Документация 4.3.2/qabstractsocket

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск
40px Внимание: Актуальная версия перевода документации находится здесь

__NOTOC__

Image:qt-logo.png

Главная · Все классы · Основные классы · Классы по группам · Модули · Функции

Image:trolltech-logo.png

Содержание

[править] Класс QAbstractSocket
[модуль QtNetwork ]

Класс QAbstractSocket предоставляет возможности, общиедля сокетов всех типов. Далее...

 #include <QAbstractSocket>

Производныйот QIODevice.

Базовый для QTcpSocketи QUdpSocket.

Примечание: Все функции этого класса потокоустойчивы.

[править] Открытые типы

  • enum NetworkLayerProtocol { IPv4Protocol, IPv6Protocol, UnknownNetworkLayerProtocol }
  • enum SocketError { ConnectionRefusedError, RemoteHostClosedError, HostNotFoundError, SocketAccessError, ..., UnknownSocketError }
  • enum SocketState { UnconnectedState, HostLookupState, ConnectingState, ConnectedState, ..., ListeningState }
  • enum SocketType { TcpSocket, UdpSocket, UnknownSocketType }

[править] Открытые функции

  • 32 открытых функций унаследованных от QIODevice
  • 29 открытых функций унаследованных от QObject

[править] Сигналы

  • 3 сигнала унаследованных от QIODevice
  • 1 сигнал унаследованный от QObject

[править] Защищенные функции

  • 5 защищенных функций унаследованных от QIODevice
  • 7 защищенных функций унаследованных от QObject

[править] Защищенные слоты

[править] Дополнительные унаследованные члены

  • 1 свойство унаследованное от QObject
  • 1 открытый слот унаследованный от QObject
  • 5 статических открытых члена унаследованных от QObject

[править] Подробное описание

Класс QAbstractSocket предоставляет возможности, общиедля сокетов всех типов.

Класс QAbstractSocket является базовым дляклассов QTcpSocketи QUdpSocket и содержитвсе возможности, общие для этих двух классов. Если вам требуетсясокет, вы можете сделать одно из двух:

  • Создать объекткласса QTcpSocketили QUdpSocket.
  • Создать собственный дескриптор сокета, создать объекткласса QAbstractSocket, и воспользоватьсяфункцией setSocketDescriptor()чтобы обернуть этот дескриптор.

TCP (Transmission Control Protocol) представляет собой надежный,поточный и ориентированный на соединение транспортныйпротокол. UDP (User Datagram Protocol) представляет собойне-надежный, датаграммный транспортный протокол без соединений. Напрактике это означает, что протокол TCP более приспособлен длянепрерывной передачи данных, в то время как более«легкий» протокол UDP можно использовать там, гденадежность менее важна.

API класса QAbstractSocket унифицирует большинстворазличий между этими протоколами. Например, хотя протокол UDPсоединений не поддерживает,функция connectToHost()создает виртуальное соединение для UDP сокетов, что дает возможностьпользоваться объектом класса QAbstractSocket более илименее одинаковым образом вне зависимости от используемогопротокола. Технически QAbstractSocket запоминает адреси порт, переданныефункции connectToHost(),а функциивроде read()и write() будутпотом использовать эти значения.

В любой момент времени объект класса QAbstractSocketнаходится в некотором состоянии (его возвращаетфункция state()). Начальнымсостояниемявляется UnconnectedState. послевызова connectToHost(),сокет переходит всостояние HostLookupState. Еслихост найден, объект QAbstractSocket переходит всостояние ConnectingStateи выбрасываетсигнал hostFound(). Когдасоединение установлено, он переходит всостояние ConnectedStateи выбрасываетсигнал connected(). Еслина любом из этих шагов происходит ошибка, выбрасываетсясигнал error(). Всякийраз, когда состояние изменяется, выбрасываетсясигнал stateChanged(). Дляудобства имеетсяфункция isValid(),которая возвращает true, если сокет готов для чтения изаписи, но учтите, что прежде, чем чтение или запись можно будетпроизводить, сокет должен находиться всостоянии ConnectedState.

Read or write data by calling read() or write(), or use the convenience functions readLine() and readAll(). QAbstractSocket also inherits getChar(), putChar(), and ungetChar() from QIODevice, which work on single bytes. For every chunk of data that has been written to the socket, the bytesWritten() signal is emitted.

The readyRead() signal is emitted every time a new chunk of data has arrived. bytesAvailable() then returns the number of bytes that are available for reading. Typically, you would connect the readyRead() signal to a slot and read all available data there. If you don't read all the data at once, the remaining data will still be available later, and any new incoming data will be appended to QAbstractSocket's internal read buffer. To limit the size of the read buffer, call setReadBufferSize().

To close the socket, call disconnectFromHost(). QAbstractSocket enters QAbstractSocket::ClosingState, then emits closing(). After all pending data has been written to the socket, QAbstractSocket actually closes the socket, enters QAbstractSocket::ClosedState, and emits disconnected(). If you want to abort a connection immediately, discarding all pending data, call abort() instead. If the remote host closes the connection, QAbstractSocket will emit error( QAbstractSocket::RemoteHostClosedError), during which the socket state will still be ConnectedState, and then the disconnected() signal will be emitted.

The port and address of the connected peer is fetched by calling peerPort() and peerAddress(). peerName() returns the host name of the peer, as passed to connectToHost(). localPort() and localAddress() return the port and address of the local socket.

QAbstractSocket provides a set of functions that suspend the calling thread until certain signals are emitted. These functions can be used to implement blocking sockets:

We show an example:

     int numRead = 0, numReadTotal = 0;
     char buffer[50];
 
     forever {
         numRead  = socket.read(buffer, 50);
 
         // do whatever with array
 
         numReadTotal += numRead;
         if (numRead == 0 &amp;&amp; !socket.waitForReadyRead())
             break;
     }

If waitForReadyRead() returns false, the connection has been closed or an error has occurred.

Programming with a blocking socket is radically different from programming with a non-blocking socket. A blocking socket doesn't require an event loop and typically leads to simpler code. However, in a GUI application, blocking sockets should only be used in non-GUI threads, to avoid freezing the user interface. See the network/fortuneclient and network/blockingfortuneclient examples for an overview of both approaches.

QAbstractSocket can be used with QTextStream and QDataStream's stream operators (operator<<() and operator>>()). There is one issue to be aware of, though: You must make sure that enough data is available before attempting to read it using operator>>().

See also QFtp, QHttp, and QTcpServer.


[править] Описание типов членов

[править]
enum QAbstractSocket::NetworkLayerProtocol

This enum describes the network layer protocol values used in Qt.


Constant Value Description
QAbstractSocket::IPv4Protocol 0 IPv4
QAbstractSocket::IPv6Protocol 1 IPv6
QAbstractSocket::UnknownNetworkLayerProtocol -1 Other than IPv4 and IPv6

See also QHostAddress::protocol().

[править]
enum QAbstractSocket::SocketError

This enum describes the socket errors that can occur.


Constant Value Description
QAbstractSocket::ConnectionRefusedError 0 The connection was refused by the peer (or timed out).
QAbstractSocket::RemoteHostClosedError 1 The remote host closed the connection. Note that the client socket (i.e., this socket) will be closed after the remote close notification has been sent.
QAbstractSocket::HostNotFoundError 2 The host address was not found.
QAbstractSocket::SocketAccessError 3 The socket operation failed because the application lacked the required privileges.
QAbstractSocket::SocketResourceError 4 The local system ran out of resources (e.g., too many sockets).
QAbstractSocket::SocketTimeoutError 5 The socket operation timed out.
QAbstractSocket::DatagramTooLargeError 6 The datagram was larger than the operating system's limit (which can be as low as 8192 bytes).
QAbstractSocket::NetworkError 7 An error occurred with the network (e.g., the network cable was accidentally plugged out).
QAbstractSocket::AddressInUseError 8 The address specified to QUdpSocket::bind() is already in use and was set to be exclusive.
QAbstractSocket::SocketAddressNotAvailableError 9 The address specified to QUdpSocket::bind() does not belong to the host.
QAbstractSocket::UnsupportedSocketOperationError 10 The requested socket operation is not supported by the local operating system (e.g., lack of IPv6 support).
QAbstractSocket::ProxyAuthenticationRequiredError 12 The socket is using a proxy, and the proxy requires authentication.
QAbstractSocket::UnknownSocketError -1 An unidentified error occurred.

Used by QAbstractSocketEngine only, this error indicates that the last operation could not complete.

See also QAbstractSocket::error().

[править]
enum QAbstractSocket::SocketState

This enum describes the different states in which a socket can be.


Constant Value Description
QAbstractSocket::UnconnectedState 0 The socket is not connected.
QAbstractSocket::HostLookupState 1 The socket is performing a host name lookup.
QAbstractSocket::ConnectingState 2 The socket has started establishing a connection.
QAbstractSocket::ConnectedState 3 A connection is established.
QAbstractSocket::BoundState 4 The socket is bound to an address and port (for servers).
QAbstractSocket::ClosingState 6 The socket is about to close (data may still be waiting to be written).
QAbstractSocket::ListeningState 5 For internal use only.

See also QAbstractSocket::state().

[править]
enum QAbstractSocket::SocketType

This enum describes the transport layer protocol.


Constant Value Description
QAbstractSocket::TcpSocket 0 TCP
QAbstractSocket::UdpSocket 1 UDP
QAbstractSocket::UnknownSocketType -1 Other than TCP and UDP

See also QAbstractSocket::socketType().


[править] Описание функций-членов

[править]
QAbstractSocket::QAbstractSocket ( SocketType socketType, QObject * parent )

Creates a new abstract socket of type socketType. The parent argument is passed to QObject's constructor.

See also socketType(), QTcpSocket, and QUdpSocket.

[править]
QAbstractSocket::~QAbstractSocket () [virtual]

Destroys the socket.

[править]
void QAbstractSocket::abort ()

Aborts the current connection and resets the socket. Unlike disconnectFromHost(), this function immediately closes the socket, clearing any pending data in the write buffer.

See also disconnectFromHost() and close().

[править]
qint64 QAbstractSocket::bytesAvailable () const [virtual]

Returns the number of incoming bytes that are waiting to be read.

Reimplemented from QIODevice.

See also bytesToWrite() and read().

[править]
qint64 QAbstractSocket::bytesToWrite () const [virtual]

Returns the number of bytes that are waiting to be written. The bytes are written when control goes back to the event loop or when flush() is called.

Reimplemented from QIODevice.

See also bytesAvailable() and flush().

[править]
bool QAbstractSocket::canReadLine () const [virtual]

Returns true if a line of data can be read from the socket; otherwise returns false.

Reimplemented from QIODevice.

See also readLine().

[править]
void QAbstractSocket::close () [virtual]

Disconnects the socket's connection with the host.

Reimplemented from QIODevice.

See also abort().

[править]
void QAbstractSocket::connectToHost ( const QString & hostName, quint16 port, OpenMode openMode = ReadWrite )

Attempts to make a connection to hostName on the given port.

The socket is opened in the given openMode and first enters HostLookupState, then performs a host name lookup of hostName. If the lookup succeeds, hostFound() is emitted and QAbstractSocket enters ConnectingState. It then attempts to connect to the address or addresses returned by the lookup. Finally, if a connection is established, QAbstractSocket enters ConnectedState and emits connected().

At any point, the socket can emit error() to signal that an error occurred.

hostName may be an IP address in string form (e.g., "43.195.83.32"), or it may be a host name (e.g., "www.trolltech.com"). QAbstractSocket will do a lookup only if required. port is in native byte order.

See also state(), peerName(), peerAddress(), peerPort(), and waitForConnected().

[править]
void QAbstractSocket::connectToHost ( const QHostAddress & address, quint16 port, OpenMode openMode = ReadWrite )

This is an overloaded member function, provided for convenience.

Attempts to make a connection to address on port port.

[править]
void QAbstractSocket::connectToHostImplementation ( const QString & hostName, quint16 port, OpenMode openMode = ReadWrite ) [protected slot]

Contains the implementation of connectToHost().

Attempts to make a connection to hostName on the given port. The socket is opened in the given openMode.

This function was introduced in Qt 4.1.

[править]
void QAbstractSocket::connected () [signal]

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

See also connectToHost() and disconnected().

[править]
void QAbstractSocket::disconnectFromHost ()

Attempts to close the socket. If there is pending data waiting to be written, QAbstractSocket will enter ClosingState and wait until all data has been written. Eventually, it will enter UnconnectedState and emit the disconnected() signal.

See also connectToHost().

[править]
void QAbstractSocket::disconnectFromHostImplementation () [protected slot]

Contains the implementation of disconnectFromHost().

This function was introduced in Qt 4.1.

[править]
void QAbstractSocket::disconnected () [signal]

This signal is emitted when the socket has been disconnected.

See also connectToHost(), disconnectFromHost(), and abort().

[править]
SocketError QAbstractSocket::error () const

Returns the type of error that last occurred.

See also state() and errorString().

[править]
void QAbstractSocket::error ( QAbstractSocket::SocketError socketError ) [signal]

This is an overloaded member function, provided for convenience.

This signal is emitted after an error occurred. The socketError parameter describes the type of error that occurred.

QAbstractSocket::SocketError is not a registered metatype, so for queued connections, you will have to register it with Q_REGISTER_METATYPE.

See also error() and errorString().

[править]
bool QAbstractSocket::flush ()

This function writes as much as possible from the internal write buffer to the underlying network socket, without blocking. If any data was written, this function returns true; otherwise false is returned.

Call this function if you need QAbstractSocket to start sending buffered data immediately. The number of bytes successfully written depends on the operating system. In most cases, you do not need to call this function, because QAbstractSocket will start sending data automatically once control goes back to the event loop. In the absence of an event loop, call waitForBytesWritten() instead.

See also write() and waitForBytesWritten().

[править]
void QAbstractSocket::hostFound () [signal]

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

See also connected().

[править]
bool QAbstractSocket::isValid () const

Returns true if the socket is valid and ready for use; otherwise returns false.

Note: The socket's state must be ConnectedState before reading and writing can occur.

See also state().

[править]
QHostAddress QAbstractSocket::localAddress () const

Returns the host address of the local socket if available; otherwise returns QHostAddress::Null.

This is normally the main IP address of the host, but can be QHostAddress::LocalHost (127.0.0.1) for connections to the local host.

See also localPort(), peerAddress(), and setLocalAddress().

[править]
quint16 QAbstractSocket::localPort () const

Returns the host port number (in native byte order) of the local socket if available; otherwise returns 0.

See also localAddress(), peerPort(), and setLocalPort().

[править]
QHostAddress QAbstractSocket::peerAddress () const

Returns the address of the connected peer if the socket is in ConnectedState; otherwise returns QHostAddress::Null.

See also peerName(), peerPort(), localAddress(), and setPeerAddress().

[править]
QString QAbstractSocket::peerName () const

Returns the name of the peer as specified by connectToHost(), or an empty QString if connectToHost() has not been called.

See also peerAddress(), peerPort(), and setPeerName().

[править]
quint16 QAbstractSocket::peerPort () const

Returns the port of the connected peer if the socket is in ConnectedState; otherwise returns 0.

See also peerAddress(), localPort(), and setPeerPort().

[править]
QNetworkProxy QAbstractSocket::proxy () const

Returns the network proxy for this socket. By default QNetworkProxy::DefaultProxy is used.

This function was introduced in Qt 4.1.

See also setProxy() and QNetworkProxy.

[править]
void QAbstractSocket::proxyAuthenticationRequired ( const QNetworkProxy & proxy, QAuthenticator * authenticator ) [signal]

This signal can be emitted when a proxy that requires authentication is used. The authenticator object can then be filled in with the required details to allow authentication and continue the connection.

Note: It is not possible to use a QueuedConnection to connect to this signal, as the connection will fail if the authenticator has not been filled in with new information when the signal returns.

This function was introduced in Qt 4.3.

See also QAuthenticator and QNetworkProxy.

[править]
qint64 QAbstractSocket::readBufferSize () const

Returns the size of the internal read buffer. This limits the amount of data that the client can receive before you call read() or readAll().

A read buffer size of 0 (the default) means that the buffer has no size limit, ensuring that no data is lost.

See also setReadBufferSize() and read().

[править]
void QAbstractSocket::setLocalAddress ( const QHostAddress & address ) [protected]

Sets the address on the local side of a connection to address.

You can call this function in a subclass of QAbstractSocket to change the return value of the localAddress() function after a connection has been established. This feature is commonly used by proxy connections for virtual connection settings.

Note that this function does not bind the local address of the socket prior to a connection (e.g., QUdpSocket::bind()).

This function was introduced in Qt 4.1.

See also localAddress(), setLocalPort(), and setPeerAddress().

[править]
void QAbstractSocket::setLocalPort ( quint16 port ) [protected]

Sets the port on the local side of a connection to port.

You can call this function in a subclass of QAbstractSocket to change the return value of the localPort() function after a connection has been established. This feature is commonly used by proxy connections for virtual connection settings.

Note that this function does not bind the local port of the socket prior to a connection (e.g., QUdpSocket::bind()).

This function was introduced in Qt 4.1.

See also localPort(), localAddress(), setLocalAddress(), and setPeerPort().

[править]
void QAbstractSocket::setPeerAddress ( const QHostAddress & address ) [protected]

Sets the address of the remote side of the connection to address.

You can call this function in a subclass of QAbstractSocket to change the return value of the peerAddress() function after a connection has been established. This feature is commonly used by proxy connections for virtual connection settings.

This function was introduced in Qt 4.1.

See also peerAddress(), setPeerPort(), and setLocalAddress().

[править]
void QAbstractSocket::setPeerName ( const QString & name ) [protected]

Sets the host name of the remote peer to name.

You can call this function in a subclass of QAbstractSocket to change the return value of the peerName() function after a connection has been established. This feature is commonly used by proxy connections for virtual connection settings.

This function was introduced in Qt 4.1.

See also peerName().

[править]
void QAbstractSocket::setPeerPort ( quint16 port ) [protected]

Sets the port of the remote side of the connection to port.

You can call this function in a subclass of QAbstractSocket to change the return value of the peerPort() function after a connection has been established. This feature is commonly used by proxy connections for virtual connection settings.

This function was introduced in Qt 4.1.

See also peerPort(), setPeerAddress(), and setLocalPort().

[править]
void QAbstractSocket::setProxy ( const QNetworkProxy & networkProxy )

Sets the explicit network proxy for this socket to networkProxy.

To disable the use of a proxy for this socket, use the QNetworkProxy::NoProxy proxy type:

 socket->setProxy(QNetworkProxy::NoProxy);

This function was introduced in Qt 4.1.

See also proxy() and QNetworkProxy.

[править]
void QAbstractSocket::setReadBufferSize ( qint64 size )

Sets the size of QAbstractSocket's internal read buffer to be size bytes.

If the buffer size is limited to a certain size, QAbstractSocket won't buffer more than this size of data. Exceptionally, a buffer size of 0 means that the read buffer is unlimited and all incoming data is buffered. This is the default.

This option is useful if you only read the data at certain points in time (e.g., in a real-time streaming application) or if you want to protect your socket against receiving too much data, which may eventually cause your application to run out of memory.

Only QTcpSocket uses QAbstractSocket's internal buffer; QUdpSocket does not use any buffering at all, but rather relies on the implicit buffering provided by the operating system. Because of this, calling this function on QUdpSocket has no effect.

See also readBufferSize() and read().

[править]
bool QAbstractSocket::setSocketDescriptor ( int socketDescriptor, SocketState socketState = ConnectedState, OpenMode openMode = ReadWrite )

Initializes QAbstractSocket with the native socket descriptor socketDescriptor. Returns true if socketDescriptor is accepted as a valid socket descriptor; otherwise returns false. The socket is opened in the mode specified by openMode, and enters the socket state specified by socketState.

Note: It is not possible to initialize two abstract sockets with the same native socket descriptor.

See also socketDescriptor().

[править]
void QAbstractSocket::setSocketError ( SocketError socketError ) [protected]

Sets the type of error that last occurred to socketError.

See also setSocketState() and setErrorString().

[править]
void QAbstractSocket::setSocketState ( SocketState state ) [protected]

Sets the state of the socket to state.

See also state().

[править]
int QAbstractSocket::socketDescriptor () const

Returns the native socket descriptor of the QAbstractSocket object if this is available; otherwise returns -1.

If the socket is using QNetworkProxy, the returned descriptor may not be usable with native socket functions.

The socket descriptor is not available when QAbstractSocket is in UnconnectedState.

See also setSocketDescriptor().

[править]
SocketType QAbstractSocket::socketType () const

Returns the socket type (TCP, UDP, or other).

See also QTcpSocket and QUdpSocket.

[править]
SocketState QAbstractSocket::state () const

Returns the state of the socket.

See also error().

[править]
void QAbstractSocket::stateChanged ( QAbstractSocket::SocketState socketState ) [signal]

This signal is emitted whenever QAbstractSocket's state changes. The socketState parameter is the new state.

QAbstractSocket::SocketState is not a registered metatype, so for queued connections, you will have to register it with Q_REGISTER_METATYPE.

See also state().

[править]
bool QAbstractSocket::waitForConnected ( int msecs = 30000 )

Waits until the socket is connected, up to msecs milliseconds. If the connection has been established, this function returns true; otherwise it returns false. In the case where it returns false, you can call error() to determine the cause of the error.

The following example waits up to one second for a connection to be established:

 socket->connectToHost("imap", 143);
 if (socket->waitForConnected(1000))
     qDebug("Connected!");

If msecs is -1, this function will not time out.

See also connectToHost() and connected().

[править]
bool QAbstractSocket::waitForDisconnected ( int msecs = 30000 )

Waits until the socket has disconnected, up to msecs milliseconds. If the connection has been disconnected, this function returns true; otherwise it returns false. In the case where it returns false, you can call error() to determine the cause of the error.

The following example waits up to one second for a connection to be closed:

 socket->disconnectFromHost();
     if (socket->state() == QAbstractSocket::UnconnectedState ||
         socket->waitForDisconnected(1000))
         qDebug("Disconnected!");

If msecs is -1, this function will not time out.

See also disconnectFromHost() and close().

[править]
bool QAbstractSocket::waitForReadyRead ( int msecs = 30000 ) [virtual]

This function blocks until data is available for reading and the readyRead() signal has been emitted. The function will timeout after msecs milliseconds; the default timeout is 3000 milliseconds.

The function returns true if data is available for reading; otherwise it returns false (if an error occurred or the operation timed out).

Reimplemented from QIODevice.

See also waitForBytesWritten().


Copyright © 2007 Trolltech Trademarks
Qt 4.3.2