The QLocalSocket class provides a local socket.More...
Header: | #include <QLocalSocket> |
qmake: | QT += network |
Since: | Qt 4.4 |
Inherits: | QIODevice |
This class was introduced in Qt 4.4.
enum | LocalSocketError { ConnectionRefusedError, PeerClosedError, ServerNotFoundError, SocketAccessError, SocketResourceError, …, UnknownSocketError } |
enum | LocalSocketState { UnconnectedState, ConnectingState, ConnectedState, ClosingState } |
QLocalSocket(QObject *parent = nullptr) | |
virtual | ~QLocalSocket() |
void | abort() |
void | connectToServer(QIODevice::OpenModeopenMode = ReadWrite) |
void | connectToServer(const QString &name, QIODevice::OpenModeopenMode = ReadWrite) |
void | disconnectFromServer() |
QLocalSocket::LocalSocketError | error() const |
bool | flush() |
QString | fullServerName() const |
bool | isValid() const |
qint64 | readBufferSize() const |
QString | serverName() const |
void | setReadBufferSize(qint64size) |
void | setServerName(const QString &name) |
bool | setSocketDescriptor(qintptrsocketDescriptor, QLocalSocket::LocalSocketStatesocketState = ConnectedState, QIODevice::OpenModeopenMode = ReadWrite) |
qintptr | socketDescriptor() const |
QLocalSocket::LocalSocketState | state() const |
bool | waitForConnected(intmsecs = 30000) |
bool | waitForDisconnected(intmsecs = 30000) |
virtual qint64 | bytesAvailable() const override |
virtual qint64 | bytesToWrite() const override |
virtual bool | canReadLine() const override |
virtual void | close() override |
virtual bool | isSequential() const override |
virtual bool | open(QIODevice::OpenModeopenMode = ReadWrite) override |
virtual bool | waitForBytesWritten(intmsecs = 30000) override |
virtual bool | waitForReadyRead(intmsecs = 30000) override |
void | connected() |
void | disconnected() |
void | errorOccurred(QLocalSocket::LocalSocketErrorsocketError) |
void | stateChanged(QLocalSocket::LocalSocketStatesocketState) |
virtual qint64 | readData(char *data, qint64c) override |
virtual qint64 | writeData(const char *data, qint64c) override |
On Windows this is a named pipe and on Unix this is a local domain socket.
If an error occurs,error() returns the type of error, anderrorString() 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 usewaitForConnected(),waitForReadyRead(),waitForBytesWritten(), andwaitForDisconnected() which blocks until the operation is complete or the timeout expires.
See alsoQLocalServer.
The LocalServerError enumeration represents the errors that can occur. The most recent error can be retrieved through a call toQLocalSocket::error().
Constant | Value | Description |
---|---|---|
QLocalSocket::ConnectionRefusedError | QAbstractSocket::ConnectionRefusedError | The connection was refused by the peer (or timed out). |
QLocalSocket::PeerClosedError | QAbstractSocket::RemoteHostClosedError | The remote socket closed the connection. Note that the client socket (i.e., this socket) will be closed after the remote close notification has been sent. |
QLocalSocket::ServerNotFoundError | QAbstractSocket::HostNotFoundError | The local socket name was not found. |
QLocalSocket::SocketAccessError | QAbstractSocket::SocketAccessError | The socket operation failed because the application lacked the required privileges. |
QLocalSocket::SocketResourceError | QAbstractSocket::SocketResourceError | The local system ran out of resources (e.g., too many sockets). |
QLocalSocket::SocketTimeoutError | QAbstractSocket::SocketTimeoutError | The socket operation timed out. |
QLocalSocket::DatagramTooLargeError | QAbstractSocket::DatagramTooLargeError | The datagram was larger than the operating system's limit (which can be as low as 8192 bytes). |
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::OperationError | QAbstractSocket::OperationError | An operation was attempted while the socket was in a state that did not permit it. |
QLocalSocket::UnknownSocketError | QAbstractSocket::UnknownSocketError | An unidentified error occurred. |
This enum describes the different states in which a socket can be.
Constant | Value | Description |
---|---|---|
QLocalSocket::UnconnectedState | QAbstractSocket::UnconnectedState | The socket is not connected. |
QLocalSocket::ConnectingState | QAbstractSocket::ConnectingState | The socket has started establishing a connection. |
QLocalSocket::ConnectedState | QAbstractSocket::ConnectedState | A connection is established. |
QLocalSocket::ClosingState | QAbstractSocket::ClosingState | The socket is about to close (data may still be waiting to be written). |
See alsoQLocalSocket::state().
Creates a new local socket. Theparent argument is passed toQObject's constructor.
[signal]
void QLocalSocket::connected()This signal is emitted afterconnectToServer() has been called and a connection has been successfully established.
See alsoconnectToServer() anddisconnected().
[signal]
void QLocalSocket::disconnected()This signal is emitted when the socket has been disconnected.
See alsoconnectToServer(),disconnectFromServer(),abort(), andconnected().
[signal]
void QLocalSocket::errorOccurred(QLocalSocket::LocalSocketErrorsocketError)This signal is emitted after an error occurred. ThesocketError parameter describes the type of error that occurred.
QLocalSocket::LocalSocketError is not a registered metatype, so for queued connections, you will have to register it withQ_DECLARE_METATYPE() andqRegisterMetaType().
This function was introduced in Qt 5.15.
See alsoerror(),errorString(), andCreating Custom Qt Types.
[signal]
void QLocalSocket::stateChanged(QLocalSocket::LocalSocketStatesocketState)This signal is emitted wheneverQLocalSocket's state changes. ThesocketState parameter is the new state.
QLocalSocket::SocketState is not a registered metatype, so for queued connections, you will have to register it withQ_DECLARE_METATYPE() andqRegisterMetaType().
See alsostate() andCreating Custom Qt Types.
[virtual]
QLocalSocket::~QLocalSocket()Destroys the socket, closing the connection if necessary.
Aborts the current connection and resets the socket. UnlikedisconnectFromServer(), this function immediately closes the socket, clearing any pending data in the write buffer.
See alsodisconnectFromServer() andclose().
[override virtual]
qint64 QLocalSocket::bytesAvailable() constReimplements:QIODevice::bytesAvailable() const.
[override virtual]
qint64 QLocalSocket::bytesToWrite() constReimplements:QIODevice::bytesToWrite() const.
[override virtual]
bool QLocalSocket::canReadLine() constReimplements:QIODevice::canReadLine() const.
[override virtual]
void QLocalSocket::close()Reimplements:QIODevice::close().
Attempts to make a connection toserverName().setServerName() must be called before you open the connection. Alternatively you can use connectToServer(constQString &name,OpenModeopenMode);
The socket is opened in the givenopenMode and first entersConnectingState. If a connection is established,QLocalSocket entersConnectedState and emitsconnected().
After calling this function, the socket can emiterrorOccurred() to signal that an error occurred.
This function was introduced in Qt 5.1.
See alsostate(),serverName(), andwaitForConnected().
This is an overloaded function.
Set the servername and attempts to make a connection to it.
The socket is opened in the givenopenMode and first entersConnectingState. If a connection is established,QLocalSocket entersConnectedState and emitsconnected().
After calling this function, the socket can emiterrorOccurred() to signal that an error occurred.
See alsostate(),serverName(), andwaitForConnected().
Attempts to close the socket. If there is pending data waiting to be written,QLocalSocket will enterClosingState and wait until all data has been written. Eventually, it will enterUnconnectedState and emit the disconnectedFromServer() signal.
See alsoconnectToServer().
Returns the type of error that last occurred.
See alsostate() anderrorString().
This function writes as much as possible from the internal write buffer to the socket, without blocking. If any data was written, this function returnstrue
; otherwise false is returned.
Call this function if you needQLocalSocket 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, becauseQLocalSocket will start sending data automatically once control goes back to the event loop. In the absence of an event loop, callwaitForBytesWritten() instead.
See alsowrite() andwaitForBytesWritten().
Returns the server path that the socket is connected to.
Note:The return value of this function is platform specific.
See alsoconnectToServer() andserverName().
[override virtual]
bool QLocalSocket::isSequential() constReimplements:QIODevice::isSequential() const.
Returnstrue
if the socket is valid and ready for use; otherwise returnsfalse
.
Note:The socket's state must beConnectedState before reading and writing can occur.
See alsostate() andconnectToServer().
[override virtual]
bool QLocalSocket::open(QIODevice::OpenModeopenMode = ReadWrite)Reimplements:QIODevice::open(QIODevice::OpenMode mode).
Equivalent toconnectToServer(OpenMode mode). The socket is opened in the givenopenMode to the server defined bysetServerName().
Note that unlike in most otherQIODevice subclasses, open() may not open the device directly. The function return false if the socket was already connected or if the server to connect to was not defined and true in any other case. Theconnected() orerrorOccurred() signals will be emitted once the device is actually open (or the connection failed).
SeeconnectToServer() for more details.
Returns the size of the internal read buffer. This limits the amount of data that the client can receive before you callread() orreadAll(). A read buffer size of 0 (the default) means that the buffer has no size limit, ensuring that no data is lost.
See alsosetReadBufferSize() andread().
[override virtual protected]
qint64 QLocalSocket::readData(char *data,qint64c)Reimplements:QIODevice::readData(char *data, qint64 maxSize).
Returns the name of the peer as specified bysetServerName(), or an emptyQString ifsetServerName() has not been called orconnectToServer() failed.
See alsosetServerName(),connectToServer(), andfullServerName().
Sets the size ofQLocalSocket's internal read buffer to besize bytes.
If the buffer size is limited to a certain size,QLocalSocket 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.
See alsoreadBufferSize() andread().
Set thename of the peer to connect to. On Windows name is the name of a named pipe; on Unix name is the name of a local domain socket.
This function must be called when the socket is not connected.
This function was introduced in Qt 5.1.
See alsoserverName().
InitializesQLocalSocket with the native socket descriptorsocketDescriptor. Returnstrue
ifsocketDescriptor is accepted as a valid socket descriptor; otherwise returnsfalse
. The socket is opened in the mode specified byopenMode, and enters the socket state specified bysocketState.
Note:It is not possible to initialize two local sockets with the same native socket descriptor.
See alsosocketDescriptor(),state(), andopenMode().
Returns the native socket descriptor of theQLocalSocket object if this is available; otherwise returns -1.
The socket descriptor is not available whenQLocalSocket is inUnconnectedState. The type of the descriptor depends on the platform:
See alsosetSocketDescriptor().
Returns the state of the socket.
See alsoerror().
[override virtual]
bool QLocalSocket::waitForBytesWritten(intmsecs = 30000)Reimplements:QIODevice::waitForBytesWritten(int msecs).
Waits until the socket is connected, up tomsecs milliseconds. If the connection has been established, this function returnstrue
; otherwise it returnsfalse
. In the case where it returnsfalse
, you can callerror() to determine the cause of the error.
The following example waits up to one second for a connection to be established:
socket->connectToServer("market");if (socket->waitForConnected(1000))qDebug("Connected!");
Ifmsecs is -1, this function will not time out.
See alsoconnectToServer() andconnected().
Waits until the socket has disconnected, up tomsecs milliseconds. If the connection was successfully disconnected, this function returnstrue
; otherwise it returnsfalse
(if the operation timed out, if an error occurred, or if thisQLocalSocket is already disconnected). In the case where it returnsfalse
, you can callerror() to determine the cause of the error.
The following example waits up to one second for a connection to be closed:
socket->disconnectFromServer();if (socket->state()==QLocalSocket::UnconnectedState|| socket->waitForDisconnected(1000)) {qDebug("Disconnected!");}
Ifmsecs is -1, this function will not time out.
See alsodisconnectFromServer() andclose().
[override virtual]
bool QLocalSocket::waitForReadyRead(intmsecs = 30000)Reimplements:QIODevice::waitForReadyRead(int msecs).
This function blocks until data is available for reading and thereadyRead() signal has been emitted. The function will timeout aftermsecs milliseconds; the default timeout is 30000 milliseconds.
The function returnstrue
if data is available for reading; otherwise it returnsfalse
(if an error occurred or the operation timed out).
See alsowaitForBytesWritten().
[override virtual protected]
qint64 QLocalSocket::writeData(constchar *data,qint64c)Reimplements:QIODevice::writeData(const char *data, qint64 maxSize).
© 2024 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of theGNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.
Qt Group includes The Qt Company Oy and its global subsidiaries and affiliates.