QLocalSocket Class Reference
|
enum | LocalSocketError { ConnectionRefusedError, PeerClosedError, ServerNotFoundError, SocketAccessError, ..., UnknownSocketError } |
enum | LocalSocketState { UnconnectedState, ConnectingState, ConnectedState, ClosingState } |
QLocalSocket ( QObject * parent = 0 ) | |
~QLocalSocket () | |
void | abort () |
void | connectToServer ( const QString & name, OpenMode openMode = ReadWrite ) |
void | disconnectFromServer () |
LocalSocketError | error () const |
bool | flush () |
QString | fullServerName () const |
bool | isValid () const |
qint64 | readBufferSize () const |
QString | serverName () const |
void | setReadBufferSize ( qint64 size ) |
bool | setSocketDescriptor ( quintptr socketDescriptor, LocalSocketState socketState = ConnectedState, OpenMode openMode = ReadWrite ) |
quintptr | socketDescriptor () const |
LocalSocketState | state () const |
bool | waitForConnected ( int msecs = 30000 ) |
bool | waitForDisconnected ( int msecs = 30000 ) |
virtual qint64 | bytesAvailable () const |
virtual qint64 | bytesToWrite () const |
virtual bool | canReadLine () const |
virtual void | close () |
virtual bool | isSequential () const |
virtual bool | waitForBytesWritten ( int msecs = 30000 ) |
virtual bool | waitForReadyRead ( int msecs = 30000 ) |
void | connected () |
void | disconnected () |
void | error ( QLocalSocket::LocalSocketError socketError ) |
void | stateChanged ( QLocalSocket::LocalSocketState socketState ) |
virtual qint64 | readData ( char * data, qint64 c ) |
virtual qint64 | writeData ( const char * data, qint64 c ) |
The QLocalSocket class provides a local socket.
On Windows this is a named pipe and on Unix this is a local domain socket.
If an error occurs, socketError() returns the type of error, and errorString() can be called to get a human readable description of what happened.
Although QLocalSocket is designed for use with an event loop, it's possible to use it without one. In that case, you must use waitForConnected(), waitForReadyRead(), waitForBytesWritten(), and waitForDisconnected() which blocks until the operation is complete or the timeout expires.
Note that this feature is not supported on versions of Windows earlier than Windows XP.
See also QLocalServer.
The LocalServerError enumeration represents the errors that can occur. The most recent error can be retrieved through a call to QLocalSocket::error().
Константа | Значение | Описание |
---|---|---|
QLocalSocket::ConnectionRefusedError | QAbstractSocket::ConnectionRefusedError | Соединение было разорвано другим узлом (или по тайм-ауту). |
QLocalSocket::PeerClosedError | QAbstractSocket::RemoteHostClosedError | The remote socket closed the connection. Помните, что сокет клиента (например, текущий сокет) будет закрыт после отправления удалённого уведомления. |
QLocalSocket::ServerNotFoundError | QAbstractSocket::HostNotFoundError | The local socket name was not found. |
QLocalSocket::SocketAccessError | QAbstractSocket::SocketAccessError | Операция с сокетом была прервана, так как приложение не получило необходимых прав. |
QLocalSocket::SocketResourceError | QAbstractSocket::SocketResourceError | У текущей системы не хватило ресурсов (например, слишком много сокетов). |
QLocalSocket::SocketTimeoutError | QAbstractSocket::SocketTimeoutError | Время для операции с сокетом истекло. |
QLocalSocket::DatagramTooLargeError | QAbstractSocket::DatagramTooLargeError | Дейтаграмма больше, чем установленное ограничение в операционной системе (которое может быть меньше, чем 8192 байт). |
QLocalSocket::ConnectionError | QAbstractSocket::NetworkError | An error occurred with the connection. |
QLocalSocket::UnsupportedSocketOperationError | QAbstractSocket::UnsupportedSocketOperationError | The requested socket operation is not supported by the local operating system. |
QLocalSocket::UnknownSocketError | QAbstractSocket::UnknownSocketError | Произошла неопределённая ошибка. |
Это перечисление описывает различные состояния сокета.
Константа | Значение | Описание |
---|---|---|
QLocalSocket::UnconnectedState | QAbstractSocket::UnconnectedState | Сокет не соединён. |
QLocalSocket::ConnectingState | QAbstractSocket::ConnectingState | Сокет начинает устанавливать соединение. |
QLocalSocket::ConnectedState | QAbstractSocket::ConnectedState | Соединение установлено. |
QLocalSocket::ClosingState | QAbstractSocket::ClosingState | Сокет готовится к закрытию (данные всё ещё ожидают записи). |
See also QLocalSocket::state().
Creates a new local socket. The parent argument is passed to QObject's constructor.
Destroys the socket, closing the connection if necessary.
Закрывает текущее соединение и перезагружает сокет. Unlike disconnectFromServer(), this function immediately closes the socket, clearing any pending data in the write buffer.
See also disconnectFromServer() and close().
Переопределено из QIODevice::bytesAvailable().
Переопределено из QIODevice::bytesToWrite().
Переопределено из QIODevice::canReadLine().
Переопределено из QIODevice::close().
Attempts to make a connection to name.
The socket is opened in the given openMode and first enters ConnectingState. Затем он пытается соединиться по адресу, полученному в результате поиска. Finally, if a connection is established, QLocalSocket enters ConnectedState and emits connected().
На любом шаге сокет может отправить сигнал об ошибке error().
See also state(), serverName(), and waitForConnected().
This signal is emitted after connectToServer() has been called and a connection has been successfully established.
See also connectToServer() and disconnected().
Попытка закрыть сокет. If there is pending data waiting to be written, QLocalSocket will enter ClosingState and wait until all data has been written. Eventually, it will enter UnconnectedState and emit the disconnectedFromServer() signal.
See also connectToServer().
Этот сигнал посылается, когда сокет разрывает соединение.
See also connectToServer(), disconnectFromServer(), abort(), and connected().
Возвращает тип последней произошедшей ошибки.
Смотрите также state() и errorString().
Этот сигнал посылается после того, как произошла ошибка. Параметр socketError описывает тип ошибки.
QLocalSocket::LocalSocketError is not a registered metatype, so for queued connections, you will have to register it with Q_DECLARE_METATYPE() and qRegisterMetaType().
Смотрите также error(), errorString() и Создание пользовательских типов Qt.
This function writes as much as possible from the internal write buffer to the socket, without blocking. Если данные были записаны, функция вернёт true; в противном случае возвращается false.
Call this function if you need QLocalSocket to start sending buffered data immediately. Число переданный байт будет зависеть от операционной системы. In most cases, you do not need to call this function, because QLocalSocket will start sending data automatically once control goes back to the event loop. Если этого не происходит, лучше вызывайте waitForBytesWritten() вместо текущей функции.
Смотрите также write() и waitForBytesWritten().
Returns the server path that the socket is connected to.
Note: The return value of this function is platform specific.
See also connectToServer() and serverName().
Переопределено из QIODevice::isSequential().
Возвращает true, если сокет корректен и готов к использованию; в противном случае возвращает false.
Замечание: Состояние сокета должно быть ConnectedState до того, как будет произведено чтение или запись.
See also state() and connectToServer().
Возвращает размер внутреннего буфера чтения. Это ограничение определяет, какой объём данных может получить клиент, прежде чем вы вызовите read() или readAll(). Размер, равный 0 (по умолчанию), означает, что буфер не ограничен, что позволяет быть уверенным в том, что данные не потеряются.
Смотрите также setReadBufferSize() и read().
Переопределено из QIODevice::readData().
Returns the name of the peer as specified by connectToServer(), or an empty QString if connectToServer() has not been called or it failed.
See also connectToServer() and fullServerName().
Sets the size of QLocalSocket's internal read buffer to be size bytes.
If the buffer size is limited to a certain size, QLocalSocket won't buffer more than this size of data. В частности, если размер буфер установлен как 0, предел не установлен, все поступающие данные буферизируются. Это значение по умолчанию.
Эта опция полезна, если вы хотите только читать данные в определённое время (например, в случае с потоковым приложением реального времени) или вы хотите защитить сокет от переполнения, что может привести к нехватке памяти.
Смотрите также readBufferSize() и read().
Initializes QLocalSocket 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 local sockets with the same native socket descriptor.
See also socketDescriptor(), state(), and openMode().
Returns the native socket descriptor of the QLocalSocket object if this is available; otherwise returns -1.
The socket descriptor is not available when QLocalSocket is in UnconnectedState.
Смотрите также setSocketDescriptor().
Возвращает состояние сокета.
Смотрите также error().
This signal is emitted whenever QLocalSocket's state changes. Параметр socketState является новым состоянием.
QLocalSocket::SocketState is not a registered metatype, so for queued connections, you will have to register it with Q_DECLARE_METATYPE() and qRegisterMetaType().
Смотрите также state() и Создание пользовательских типов Qt.
Переопределено из QIODevice::waitForBytesWritten().
Ждёт msecs миллисекунд, пока установится соединение. Если соединение установлено, возвращает true; если нет - false. В случае, если функция возвращает false, вы можете вызвать error() для определения, что за ошибка произошла.
Следующий пример ждёт одну секунду для установления соединения:
socket->connectToServer("market"); if (socket->waitForConnected(1000)) qDebug("Соединено!");
If msecs is -1, this function will not time out.
See also connectToServer() and connected().
Ждёт msecs миллисекунд, пока сокет разорвёт соединение. Если соединение разорвано, функция возвращает true; если нет - false. В случае, если функция возвращает false, вы можете вызвать error() для определения, что за ошибка произошла.
Следующий пример ждёт до разрыва соединения одну секунду:
socket->disconnectFromServer(); if (socket->waitForDisconnected(1000)) qDebug("Отсоединено!");
If msecs is -1, this function will not time out.
See also disconnectFromServer() and close().
Переопределено из QIODevice::waitForReadyRead().
Эта функция блокирует сокет, пока данные, доступные для чтения, не будут прочитаны с помощью readyRead() и соответствующий сигнал не будет послан. Эта функция имеет тайм-аут после msecs миллисекунд; по умолчанию тайм-аут равен 30000 мс.
Функция возвращает true, если данные доступны для чтения; в противном случае возвращается false (если произошла ошибка или прошло время таймаута).
Смотрите также waitForBytesWritten().
Переопределено из QIODevice::writeData().
Авторские права © 2010 Nokia Corporation и/или её дочерние компании | Торговые марки | Qt 4.6.4 |
Попытка перевода Qt документации. Если есть желание присоединиться, или если есть замечания или пожелания, то заходите на форум: Перевод Qt документации на русский язык... Люди внесшие вклад в перевод: Команда переводчиков |