QLocalSocket Class

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.

Public Types

enum LocalSocketError { ConnectionRefusedError, PeerClosedError, ServerNotFoundError, SocketAccessError, SocketResourceError, …, UnknownSocketError }
enum LocalSocketState { UnconnectedState, ConnectingState, ConnectedState, ClosingState }

Public Functions

QLocalSocket(QObject *parent = nullptr)
virtual ~QLocalSocket()
void abort()
void connectToServer(QIODevice::OpenMode openMode = ReadWrite)
void connectToServer(const QString &name, QIODevice::OpenMode openMode = ReadWrite)
void disconnectFromServer()
QLocalSocket::LocalSocketError error() const
bool flush()
QString fullServerName() const
bool isValid() const
qint64 readBufferSize() const
QString serverName() const
void setReadBufferSize(qint64 size)
void setServerName(const QString &name)
bool setSocketDescriptor(qintptr socketDescriptor, QLocalSocket::LocalSocketState socketState = ConnectedState, QIODevice::OpenMode openMode = ReadWrite)
qintptr socketDescriptor() const
QLocalSocket::LocalSocketState state() const
bool waitForConnected(int msecs = 30000)
bool waitForDisconnected(int msecs = 30000)

Reimplemented Public Functions

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::OpenMode openMode = ReadWrite) override
virtual bool waitForBytesWritten(int msecs = 30000) override
virtual bool waitForReadyRead(int msecs = 30000) override

Signals

void connected()
void disconnected()
void error(QLocalSocket::LocalSocketError socketError)
void stateChanged(QLocalSocket::LocalSocketState socketState)

Reimplemented Protected Functions

virtual qint64 readData(char *data, qint64 c) override
virtual qint64 writeData(const char *data, qint64 c) override

Detailed Description

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.

See also QLocalServer.

Member Type Documentation

enum QLocalSocket::LocalSocketError

The LocalServerError enumeration represents the errors that can occur. The most recent error can be retrieved through a call to QLocalSocket::error().

ConstantValueDescription
QLocalSocket::ConnectionRefusedErrorQAbstractSocket::ConnectionRefusedErrorThe connection was refused by the peer (or timed out).
QLocalSocket::PeerClosedErrorQAbstractSocket::RemoteHostClosedErrorThe 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::ServerNotFoundErrorQAbstractSocket::HostNotFoundErrorThe local socket name was not found.
QLocalSocket::SocketAccessErrorQAbstractSocket::SocketAccessErrorThe socket operation failed because the application lacked the required privileges.
QLocalSocket::SocketResourceErrorQAbstractSocket::SocketResourceErrorThe local system ran out of resources (e.g., too many sockets).
QLocalSocket::SocketTimeoutErrorQAbstractSocket::SocketTimeoutErrorThe socket operation timed out.
QLocalSocket::DatagramTooLargeErrorQAbstractSocket::DatagramTooLargeErrorThe datagram was larger than the operating system's limit (which can be as low as 8192 bytes).
QLocalSocket::ConnectionErrorQAbstractSocket::NetworkErrorAn error occurred with the connection.
QLocalSocket::UnsupportedSocketOperationErrorQAbstractSocket::UnsupportedSocketOperationErrorThe requested socket operation is not supported by the local operating system.
QLocalSocket::OperationErrorQAbstractSocket::OperationErrorAn operation was attempted while the socket was in a state that did not permit it.
QLocalSocket::UnknownSocketErrorQAbstractSocket::UnknownSocketErrorAn unidentified error occurred.

enum QLocalSocket::LocalSocketState

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

ConstantValueDescription
QLocalSocket::UnconnectedStateQAbstractSocket::UnconnectedStateThe socket is not connected.
QLocalSocket::ConnectingStateQAbstractSocket::ConnectingStateThe socket has started establishing a connection.
QLocalSocket::ConnectedStateQAbstractSocket::ConnectedStateA connection is established.
QLocalSocket::ClosingStateQAbstractSocket::ClosingStateThe socket is about to close (data may still be waiting to be written).

See also QLocalSocket::state().

Member Function Documentation

QLocalSocket::QLocalSocket(QObject *parent = nullptr)

Creates a new local socket. The parent argument is passed to QObject's constructor.

[signal] void QLocalSocket::connected()

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

See also connectToServer() and disconnected().

[signal] void QLocalSocket::disconnected()

This signal is emitted when the socket has been disconnected.

See also connectToServer(), disconnectFromServer(), abort(), and connected().

[signal] void QLocalSocket::error(QLocalSocket::LocalSocketError socketError)

This signal is emitted after an error occurred. The socketError 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 with Q_DECLARE_METATYPE() and qRegisterMetaType().

Note: Signal error is overloaded in this class. To connect to this signal by using the function pointer syntax, Qt provides a convenient helper for obtaining the function pointer as shown in this example:

connect(localSocket, QOverload<QLocalSocket::LocalSocketError>::of(&QLocalSocket::error),
    [=](QLocalSocket::LocalSocketError socketError){ /* ... */ });

See also error(), errorString(), and Creating Custom Qt Types.

[signal] void QLocalSocket::stateChanged(QLocalSocket::LocalSocketState socketState)

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

QLocalSocket::SocketState is not a registered metatype, so for queued connections, you will have to register it with Q_DECLARE_METATYPE() and qRegisterMetaType().

See also state() and Creating Custom Qt Types.

[virtual] QLocalSocket::~QLocalSocket()

Destroys the socket, closing the connection if necessary.

void QLocalSocket::abort()

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

See also disconnectFromServer() and close().

[override virtual] qint64 QLocalSocket::bytesAvailable() const

Reimplements: QIODevice::bytesAvailable() const.

[override virtual] qint64 QLocalSocket::bytesToWrite() const

Reimplements: QIODevice::bytesToWrite() const.

[override virtual] bool QLocalSocket::canReadLine() const

Reimplements: QIODevice::canReadLine() const.

[override virtual] void QLocalSocket::close()

Reimplements: QIODevice::close().

void QLocalSocket::connectToServer(QIODevice::OpenMode openMode = ReadWrite)

Attempts to make a connection to serverName(). setServerName() must be called before you open the connection. Alternatively you can use connectToServer(const QString &name, OpenMode openMode);

The socket is opened in the given openMode and first enters ConnectingState. If a connection is established, QLocalSocket enters ConnectedState and emits connected().

After calling this function, the socket can emit error() to signal that an error occurred.

This function was introduced in Qt 5.1.

See also state(), serverName(), and waitForConnected().

void QLocalSocket::connectToServer(const QString &name, QIODevice::OpenMode openMode = ReadWrite)

This is an overloaded function.

Set the server name and attempts to make a connection to it.

The socket is opened in the given openMode and first enters ConnectingState. If a connection is established, QLocalSocket enters ConnectedState and emits connected().

After calling this function, the socket can emit error() to signal that an error occurred.

See also state(), serverName(), and waitForConnected().

void QLocalSocket::disconnectFromServer()

Attempts to close the socket. 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().

QLocalSocket::LocalSocketError QLocalSocket::error() const

Returns the type of error that last occurred.

See also state() and errorString().

bool QLocalSocket::flush()

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

Call this function if you need QLocalSocket 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 QLocalSocket 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().

QString QLocalSocket::fullServerName() const

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

[override virtual] bool QLocalSocket::isSequential() const

Reimplements: QIODevice::isSequential() const.

bool QLocalSocket::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() and connectToServer().

[override virtual] bool QLocalSocket::open(QIODevice::OpenMode openMode = ReadWrite)

Reimplements: QIODevice::open(QIODevice::OpenMode mode).

Equivalent to connectToServer(OpenMode mode). The socket is opened in the given openMode to the server defined by setServerName().

Note that unlike in most other QIODevice 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. The connected() or error() signals will be emitted once the device is actualy open (or the connection failed).

See connectToServer() for more details.

qint64 QLocalSocket::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().

[override virtual protected] qint64 QLocalSocket::readData(char *data, qint64 c)

Reimplements: QIODevice::readData(char *data, qint64 maxSize).

QString QLocalSocket::serverName() const

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

See also setServerName(), 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. 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 also readBufferSize() and read().

void QLocalSocket::setServerName(const QString &name)

Set the name 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 also serverName().

bool QLocalSocket::setSocketDescriptor(qintptr socketDescriptor, QLocalSocket::LocalSocketState socketState = ConnectedState, QIODevice::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().

qintptr QLocalSocket::socketDescriptor() const

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. The type of the descriptor depends on the platform:

  • On Windows, the returned value is a Winsock 2 Socket Handle.
  • With WinRT and on INTEGRITY, the returned value is the QTcpSocket socket descriptor and the type is defined by socketDescriptor.
  • On all other UNIX-like operating systems, the type is a file descriptor representing a socket.

See also setSocketDescriptor().

QLocalSocket::LocalSocketState QLocalSocket::state() const

Returns the state of the socket.

See also error().

[override virtual] bool QLocalSocket::waitForBytesWritten(int msecs = 30000)

Reimplements: QIODevice::waitForBytesWritten(int msecs).

bool QLocalSocket::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->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)

Waits until the socket has disconnected, up to msecs milliseconds. If the connection was successfully disconnected, this function returns true; otherwise it returns false (if the operation timed out, if an error occurred, or if this QLocalSocket is already disconnected). 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->disconnectFromServer();
if (socket->state() == QLocalSocket::UnconnectedState
    || socket->waitForDisconnected(1000)) {
    qDebug("Disconnected!");
}

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

See also disconnectFromServer() and close().

[override virtual] bool QLocalSocket::waitForReadyRead(int msecs = 30000)

Reimplements: QIODevice::waitForReadyRead(int msecs).

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 30000 milliseconds.

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

See also waitForBytesWritten().

[override virtual protected] qint64 QLocalSocket::writeData(const char *data, qint64 c)

Reimplements: QIODevice::writeData(const char *data, qint64 maxSize).

© 2020 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 the GNU 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.