QLocalSocket Class ReferenceThe QLocalSocket class provides a local socket. Далее... #include <QLocalSocket> Унаследован от: QIODevice. Этот класс был введён в Qt 4.4. Открытые типы
Открытые функции
Переопределённые открытые функции
Сигналы
Переопределённые защищённые функции
Дополнительные унаследованные члены
Подробное описание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. Описание типов-членовenum QLocalSocket::LocalSocketErrorThe LocalServerError enumeration represents the errors that can occur. The most recent error can be retrieved through a call to QLocalSocket::error().
enum QLocalSocket::LocalSocketStateЭто перечисление описывает различные состояния сокета.
See also QLocalSocket::state(). Описание функций-членовQLocalSocket::QLocalSocket ( QObject * parent = 0 )Creates a new local socket. The parent argument is passed to QObject's constructor. QLocalSocket::~QLocalSocket ()Destroys the socket, closing the connection if necessary. void QLocalSocket::abort ()Закрывает текущее соединение и перезагружает сокет. Unlike disconnectFromServer(), this function immediately closes the socket, clearing any pending data in the write buffer. See also disconnectFromServer() and close(). qint64 QLocalSocket::bytesAvailable () const [virtual]Переопределено из QIODevice::bytesAvailable(). qint64 QLocalSocket::bytesToWrite () const [virtual]Переопределено из QIODevice::bytesToWrite(). bool QLocalSocket::canReadLine () const [virtual]Переопределено из QIODevice::canReadLine(). void QLocalSocket::close () [virtual]Переопределено из QIODevice::close(). void QLocalSocket::connectToServer ( const QString & name, OpenMode openMode = ReadWrite )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(). void QLocalSocket::connected () [signal]This signal is emitted after connectToServer() has been called and a connection has been successfully established. See also connectToServer() and disconnected(). void QLocalSocket::disconnectFromServer ()Попытка закрыть сокет. 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(). void QLocalSocket::disconnected () [signal]Этот сигнал посылается, когда сокет разрывает соединение. See also connectToServer(), disconnectFromServer(), abort(), and connected(). LocalSocketError QLocalSocket::error () constВозвращает тип последней произошедшей ошибки. Смотрите также state() и errorString(). void QLocalSocket::error ( QLocalSocket::LocalSocketError socketError ) [signal]Этот сигнал посылается после того, как произошла ошибка. Параметр 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. bool QLocalSocket::flush ()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(). QString QLocalSocket::fullServerName () constReturns the server path that the socket is connected to. Note: The return value of this function is platform specific. See also connectToServer() and serverName(). bool QLocalSocket::isSequential () const [virtual]Переопределено из QIODevice::isSequential(). bool QLocalSocket::isValid () constВозвращает true, если сокет корректен и готов к использованию; в противном случае возвращает false. Замечание: Состояние сокета должно быть ConnectedState до того, как будет произведено чтение или запись. See also state() and connectToServer(). qint64 QLocalSocket::readBufferSize () constВозвращает размер внутреннего буфера чтения. Это ограничение определяет, какой объём данных может получить клиент, прежде чем вы вызовите read() или readAll(). Размер, равный 0 (по умолчанию), означает, что буфер не ограничен, что позволяет быть уверенным в том, что данные не потеряются. Смотрите также setReadBufferSize() и read(). qint64 QLocalSocket::readData ( char * data, qint64 c ) [virtual protected]Переопределено из QIODevice::readData(). QString QLocalSocket::serverName () constReturns 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(). void QLocalSocket::setReadBufferSize ( qint64 size )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(). bool QLocalSocket::setSocketDescriptor ( quintptr socketDescriptor, LocalSocketState socketState = ConnectedState, OpenMode openMode = ReadWrite )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(). quintptr QLocalSocket::socketDescriptor () constReturns 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(). LocalSocketState QLocalSocket::state () constВозвращает состояние сокета. Смотрите также error(). void QLocalSocket::stateChanged ( QLocalSocket::LocalSocketState socketState ) [signal]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. bool QLocalSocket::waitForBytesWritten ( int msecs = 30000 ) [virtual]Переопределено из QIODevice::waitForBytesWritten(). bool QLocalSocket::waitForConnected ( int msecs = 30000 )Ждёт msecs миллисекунд, пока установится соединение. Если соединение установлено, возвращает true; если нет - false. В случае, если функция возвращает false, вы можете вызвать error() для определения, что за ошибка произошла. Следующий пример ждёт одну секунду для установления соединения: socket->connectToServer("market"); if (socket->waitForConnected(1000)) qDebug("Connected!"); If msecs is -1, this function will not time out. See also connectToServer() and connected(). bool QLocalSocket::waitForDisconnected ( int msecs = 30000 )Ждёт msecs миллисекунд, пока сокет разорвёт соединение. Если соединение разорвано, функция возвращает true; если нет - false. В случае, если функция возвращает false, вы можете вызвать error() для определения, что за ошибка произошла. Следующий пример ждёт до разрыва соединения одну секунду: socket->disconnectFromServer(); if (socket->waitForDisconnected(1000)) qDebug("Disconnected!"); If msecs is -1, this function will not time out. See also disconnectFromServer() and close(). bool QLocalSocket::waitForReadyRead ( int msecs = 30000 ) [virtual]Переопределено из QIODevice::waitForReadyRead(). Эта функция блокирует сокет, пока данные, доступные для чтения, не будут прочитаны с помощью readyRead() и соответствующий сигнал не будет послан. Эта функция имеет тайм-аут после msecs миллисекунд; по умолчанию тайм-аут равен 30000 мс. Функция возвращает true, если данные доступны для чтения; в противном случае возвращается false (если произошла ошибка или прошло время таймаута). Смотрите также waitForBytesWritten(). qint64 QLocalSocket::writeData ( const char * data, qint64 c ) [virtual protected]Переопределено из QIODevice::writeData(). |
Попытка перевода Qt документации. Если есть желание присоединиться, или если есть замечания или пожелания, то заходите на форум: Перевод Qt документации на русский язык... Люди внесшие вклад в перевод: Команда переводчиков |