Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
QLocalServer Class Reference

The QLocalServer class provides a local socket based server. More...

#include <qlocalserver.h>

+ Inheritance diagram for QLocalServer:
+ Collaboration diagram for QLocalServer:

Public Types

enum  SocketOption {
  NoOptions = 0x0 , UserAccessOption = 0x01 , GroupAccessOption = 0x2 , OtherAccessOption = 0x4 ,
  WorldAccessOption = 0x7 , AbstractNamespaceOption = 0x8
}
 

Signals

void newConnection ()
 This signal is emitted every time a new connection is available.
 
- Signals inherited from QObject
void destroyed (QObject *=nullptr)
 This signal is emitted immediately before the object obj is destroyed, after any instances of QPointer have been notified, and cannot be blocked.
 
void objectNameChanged (const QString &objectName, QPrivateSignal)
 This signal is emitted after the object's name has been changed.
 

Public Member Functions

 QLocalServer (QObject *parent=nullptr)
 Create a new local socket server with the given parent.
 
 ~QLocalServer ()
 Destroys the QLocalServer object.
 
void close ()
 Stop listening for incoming connections.
 
QString errorString () const
 Returns the human-readable message appropriate to the current error reported by serverError().
 
virtual bool hasPendingConnections () const
 Returns true if the server has a pending connection; otherwise returns false.
 
bool isListening () const
 Returns true if the server is listening for incoming connections otherwise false.
 
bool listen (const QString &name)
 Tells the server to listen for incoming connections on name.
 
bool listen (qintptr socketDescriptor)
 
int maxPendingConnections () const
 Returns the maximum number of pending accepted connections.
 
virtual QLocalSocketnextPendingConnection ()
 Returns the next pending connection as a connected QLocalSocket object.
 
QString serverName () const
 Returns the server name if the server is listening for connections; otherwise returns QString()
 
QString fullServerName () const
 Returns the full path that the server is listening on.
 
QAbstractSocket::SocketError serverError () const
 Returns the type of error that occurred last or NoError.
 
void setMaxPendingConnections (int numConnections)
 Sets the maximum number of pending accepted connections to numConnections.
 
bool waitForNewConnection (int msec=0, bool *timedOut=nullptr)
 Waits for at most msec milliseconds or until an incoming connection is available.
 
void setListenBacklogSize (int size)
 Sets the backlog queue size of to be accepted connections to size.
 
int listenBacklogSize () const
 Returns the backlog queue size of to be accepted connections.
 
void setSocketOptions (SocketOptions options)
 
SocketOptions socketOptions () const
 
QBindable< SocketOptions > bindableSocketOptions ()
 
qintptr socketDescriptor () const
 
- Public Member Functions inherited from QObject
Q_INVOKABLE QObject (QObject *parent=nullptr)
 Constructs an object with parent object parent.
 
virtual ~QObject ()
 Destroys the object, deleting all its child objects.
 
virtual bool event (QEvent *event)
 This virtual function receives events to an object and should return true if the event e was recognized and processed.
 
virtual bool eventFilter (QObject *watched, QEvent *event)
 Filters events if this object has been installed as an event filter for the watched object.
 
QString objectName () const
 
Q_WEAK_OVERLOAD void setObjectName (const QString &name)
 Sets the object's name to name.
 
void setObjectName (QAnyStringView name)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
QBindable< QStringbindableObjectName ()
 
bool isWidgetType () const
 Returns true if the object is a widget; otherwise returns false.
 
bool isWindowType () const
 Returns true if the object is a window; otherwise returns false.
 
bool isQuickItemType () const
 Returns true if the object is a QQuickItem; otherwise returns false.
 
bool signalsBlocked () const noexcept
 Returns true if signals are blocked; otherwise returns false.
 
bool blockSignals (bool b) noexcept
 If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it).
 
QThreadthread () const
 Returns the thread in which the object lives.
 
bool moveToThread (QThread *thread QT6_DECL_NEW_OVERLOAD_TAIL)
 Changes the thread affinity for this object and its children and returns true on success.
 
int startTimer (int interval, Qt::TimerType timerType=Qt::CoarseTimer)
 This is an overloaded function that will start a timer of type timerType and a timeout of interval milliseconds.
 
int startTimer (std::chrono::nanoseconds time, Qt::TimerType timerType=Qt::CoarseTimer)
 
void killTimer (int id)
 Kills the timer with timer identifier, id.
 
void killTimer (Qt::TimerId id)
 
template<typename T >
findChild (QAnyStringView aName, Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 Returns the child of this object that can be cast into type T and that is called name, or \nullptr if there is no such object.
 
template<typename T >
QList< T > findChildren (QAnyStringView aName, Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects.
 
template<typename T >
findChild (Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
template<typename T >
QList< T > findChildren (Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
const QObjectListchildren () const
 Returns a list of child objects.
 
void setParent (QObject *parent)
 Makes the object a child of parent.
 
void installEventFilter (QObject *filterObj)
 Installs an event filter filterObj on this object.
 
void removeEventFilter (QObject *obj)
 Removes an event filter object obj from this object.
 
QMetaObject::Connection connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const
 
bool disconnect (const char *signal=nullptr, const QObject *receiver=nullptr, const char *member=nullptr) const
 
bool disconnect (const QObject *receiver, const char *member=nullptr) const
 
void dumpObjectTree () const
 Dumps a tree of children to the debug output.
 
void dumpObjectInfo () const
 Dumps information about signal connections, etc.
 
bool setProperty (const char *name, const QVariant &value)
 Sets the value of the object's name property to value.
 
bool setProperty (const char *name, QVariant &&value)
 
QVariant property (const char *name) const
 Returns the value of the object's name property.
 
QList< QByteArraydynamicPropertyNames () const
 
QBindingStoragebindingStorage ()
 
const QBindingStoragebindingStorage () const
 
QObjectparent () const
 Returns a pointer to the parent object.
 
bool inherits (const char *classname) const
 Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false.
 

Static Public Member Functions

static bool removeServer (const QString &name)
 
- Static Public Member Functions inherited from QObject
static QMetaObject::Connection connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
 \threadsafe
 
static QMetaObject::Connection connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection)
 
template<typename Func1 , typename Func2 >
static QMetaObject::Connection connect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, const typename QtPrivate::ContextTypeForFunctor< Func2 >::ContextType *context, Func2 &&slot, Qt::ConnectionType type=Qt::AutoConnection)
 
template<typename Func1 , typename Func2 >
static QMetaObject::Connection connect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, Func2 &&slot)
 
static bool disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member)
 \threadsafe
 
static bool disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member)
 
static bool disconnect (const QMetaObject::Connection &)
 Disconnect a connection.
 
template<typename Func1 , typename Func2 >
static bool disconnect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, const typename QtPrivate::FunctionPointer< Func2 >::Object *receiver, Func2 slot)
 
template<typename Func1 >
static bool disconnect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, const QObject *receiver, void **zero)
 

Protected Member Functions

virtual void incomingConnection (quintptr socketDescriptor)
 This virtual function is called by QLocalServer when a new connection is available.
 
void addPendingConnection (QLocalSocket *socket)
 This function is called by QLocalServer::incomingConnection() to add the socket to the list of pending incoming connections.
 
- Protected Member Functions inherited from QObject
QObjectsender () const
 Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns \nullptr.
 
int senderSignalIndex () const
 
int receivers (const char *signal) const
 Returns the number of receivers connected to the signal.
 
bool isSignalConnected (const QMetaMethod &signal) const
 
virtual void timerEvent (QTimerEvent *event)
 This event handler can be reimplemented in a subclass to receive timer events for the object.
 
virtual void childEvent (QChildEvent *event)
 This event handler can be reimplemented in a subclass to receive child events.
 
virtual void customEvent (QEvent *event)
 This event handler can be reimplemented in a subclass to receive custom events.
 
virtual void connectNotify (const QMetaMethod &signal)
 
virtual void disconnectNotify (const QMetaMethod &signal)
 
 QObject (QObjectPrivate &dd, QObject *parent=nullptr)
 

Properties

SocketOptions socketOptions
 the socket options that control how the socket operates.
 
- Properties inherited from QObject
QString objectName
 the name of this object
 

Additional Inherited Members

- Public Slots inherited from QObject
void deleteLater ()
 \threadsafe
 
- Protected Attributes inherited from QObject
QScopedPointer< QObjectDatad_ptr
 

Detailed Description

The QLocalServer class provides a local socket based server.

Since
4.4 \inmodule QtNetwork

This class makes it possible to accept incoming local socket connections.

Call listen() to have the server start listening for incoming connections on a specified key. The newConnection() signal is then emitted each time a client connects to the server.

Call nextPendingConnection() to accept the pending connection as a connected QLocalSocket. The function returns a pointer to a QLocalSocket that can be used for communicating with the client.

If an error occurs, serverError() returns the type of error, and errorString() can be called to get a human readable description of what happened.

When listening for connections, the name which the server is listening on is available through serverName().

Calling close() makes QLocalServer stop listening for incoming connections.

Although QLocalServer is designed for use with an event loop, it's possible to use it without one. In that case, you must use waitForNewConnection(), which blocks until either a connection is available or a timeout expires.

See also
QLocalSocket, QTcpServer

Definition at line 19 of file qlocalserver.h.

Member Enumeration Documentation

◆ SocketOption

Since
5.0

This enum describes the possible options that can be used to create the socket. This changes the access permissions on platforms (Linux, Windows) that support access permissions on the socket. Both GroupAccess and OtherAccess may vary slightly in meanings depending on the platform. On Linux and Android it is possible to use sockets with abstract addresses; socket permissions have no meaning for such sockets.

\value NoOptions No access restrictions have been set. \value UserAccessOption Access is restricted to the same user as the process that created the socket. \value GroupAccessOption Access is restricted to the same group but not the user that created the socket on Linux. Access is restricted to the primary group of the process on Windows \value OtherAccessOption Access is available to everyone but the user and group that created the socket on Linux. Access is available to everyone on Windows. \value WorldAccessOption No access restrictions. \value AbstractNamespaceOption The listening socket will be created in the abstract namespace. This flag is specific to Linux. In case of other platforms, for the sake of code portability, this flag is equivalent to WorldAccessOption.

See also
socketOptions
Enumerator
NoOptions 
UserAccessOption 
GroupAccessOption 
OtherAccessOption 
WorldAccessOption 
AbstractNamespaceOption 

Definition at line 30 of file qlocalserver.h.

Constructor & Destructor Documentation

◆ QLocalServer()

QLocalServer::QLocalServer ( QObject * parent = nullptr)
explicit

Create a new local socket server with the given parent.

See also
listen()

Definition at line 87 of file qlocalserver.cpp.

◆ ~QLocalServer()

QLocalServer::~QLocalServer ( )

Destroys the QLocalServer object.

If the server is listening for connections, it is automatically closed.

Any client QLocalSockets that are still connected must either disconnect or be reparented before the server is deleted.

See also
close()

Definition at line 103 of file qlocalserver.cpp.

Member Function Documentation

◆ addPendingConnection()

void QLocalServer::addPendingConnection ( QLocalSocket * socket)
protected

This function is called by QLocalServer::incomingConnection() to add the socket to the list of pending incoming connections.

Note
Don't forget to call this member from reimplemented incomingConnection() if you do not want to break the Pending Connections mechanism. This function emits the newConnection() signal after the socket has been added.
See also
incomingConnection(), newConnection()
Since
6.8

Definition at line 286 of file qlocalserver.cpp.

◆ bindableSocketOptions()

QBindable< QLocalServer::SocketOptions > QLocalServer::bindableSocketOptions ( )

Definition at line 165 of file qlocalserver.cpp.

◆ close()

void QLocalServer::close ( )

Stop listening for incoming connections.

Existing connections are not affected, but any new connections will be refused.

See also
isListening(), listen()

Definition at line 212 of file qlocalserver.cpp.

◆ errorString()

QString QLocalServer::errorString ( ) const

Returns the human-readable message appropriate to the current error reported by serverError().

If no suitable string is available, an empty string is returned.

See also
serverError()

Definition at line 233 of file qlocalserver.cpp.

◆ fullServerName()

QString QLocalServer::fullServerName ( ) const

Returns the full path that the server is listening on.

Note: This is platform specific

See also
listen(), serverName()

Definition at line 473 of file qlocalserver.cpp.

◆ hasPendingConnections()

bool QLocalServer::hasPendingConnections ( ) const
virtual

Returns true if the server has a pending connection; otherwise returns false.

See also
nextPendingConnection(), setMaxPendingConnections()

Definition at line 245 of file qlocalserver.cpp.

◆ incomingConnection()

void QLocalServer::incomingConnection ( quintptr socketDescriptor)
protectedvirtual

This virtual function is called by QLocalServer when a new connection is available.

socketDescriptor is the native socket descriptor for the accepted connection.

The base implementation creates a QLocalSocket, sets the socket descriptor and then stores the QLocalSocket in an internal list of pending connections. Finally newConnection() is emitted.

Reimplement this function to alter the server's behavior when a connection is available.

See also
newConnection(), nextPendingConnection(), QLocalSocket::setSocketDescriptor()

Definition at line 266 of file qlocalserver.cpp.

◆ isListening()

bool QLocalServer::isListening ( ) const

Returns true if the server is listening for incoming connections otherwise false.

See also
listen(), close()

Definition at line 299 of file qlocalserver.cpp.

◆ listen() [1/2]

bool QLocalServer::listen ( const QString & name)

Tells the server to listen for incoming connections on name.

If the server is currently listening then it will return false. Return true on success otherwise false.

name can be a single name and QLocalServer will determine the correct platform specific path. serverName() will return the name that is passed into listen.

Usually you would just pass in a name like "foo", but on Unix this could also be a path such as "/tmp/foo" and on Windows this could be a pipe path such as "\\\\.\\pipe\\foo"

Note
On Unix if the server crashes without closing listen will fail with AddressInUseError. To create a new server the file should be removed. On Windows two local servers can listen to the same pipe at the same time, but any connections will go to one of the server.
See also
serverName(), isListening(), close()

Definition at line 325 of file qlocalserver.cpp.

◆ listen() [2/2]

bool QLocalServer::listen ( qintptr socketDescriptor)
Since
5.0

Instructs the server to listen for incoming connections on socketDescriptor. The property returns false if the server is currently listening. It returns true on success; otherwise, it returns false. The socket must be ready to accept new connections with no extra platform-specific functions called. The socket is set into non-blocking mode.

serverName(), fullServerName() may return a string with a name if this option is supported by the platform; otherwise, they return an empty QString. In particular, the addresses of sockets in the abstract namespace supported by Linux will not yield useful names if they contain unprintable characters.

See also
isListening(), close()

Definition at line 368 of file qlocalserver.cpp.

◆ listenBacklogSize()

int QLocalServer::listenBacklogSize ( ) const

Returns the backlog queue size of to be accepted connections.

Since
6.3
See also
setListenBacklogSize()

Definition at line 564 of file qlocalserver.cpp.

◆ maxPendingConnections()

int QLocalServer::maxPendingConnections ( ) const

Returns the maximum number of pending accepted connections.

The default is 30.

See also
setMaxPendingConnections(), hasPendingConnections()

Definition at line 392 of file qlocalserver.cpp.

◆ newConnection

void QLocalServer::newConnection ( )
signal

This signal is emitted every time a new connection is available.

See also
hasPendingConnections(), nextPendingConnection()

◆ nextPendingConnection()

QLocalSocket * QLocalServer::nextPendingConnection ( )
virtual

Returns the next pending connection as a connected QLocalSocket object.

The socket is created as a child of the server, which means that it is automatically deleted when the QLocalServer object is destroyed. It is still a good idea to delete the object explicitly when you are done with it, to avoid wasting memory.

\nullptr is returned if this function is called when there are no pending connections.

See also
hasPendingConnections(), newConnection(), incomingConnection()

Definition at line 419 of file qlocalserver.cpp.

◆ removeServer()

bool QLocalServer::removeServer ( const QString & name)
static
Since
4.5

Removes any server instance that might cause a call to listen() to fail and returns true if successful; otherwise returns false. This function is meant to recover from a crash, when the previous server instance has not been cleaned up.

On Windows, this function does nothing; on Unix, it removes the socket file given by name.

Warning
Be careful to avoid removing sockets of running instances.

Definition at line 449 of file qlocalserver.cpp.

◆ serverError()

QAbstractSocket::SocketError QLocalServer::serverError ( ) const

Returns the type of error that occurred last or NoError.

See also
errorString()

Definition at line 484 of file qlocalserver.cpp.

◆ serverName()

QString QLocalServer::serverName ( ) const

Returns the server name if the server is listening for connections; otherwise returns QString()

See also
listen(), fullServerName()

Definition at line 460 of file qlocalserver.cpp.

◆ setListenBacklogSize()

void QLocalServer::setListenBacklogSize ( int size)

Sets the backlog queue size of to be accepted connections to size.

The operating system might reduce or ignore this value. By default, the queue size is 50.

Note
This property must be set prior to calling listen().
Since
6.3
See also
listenBacklogSize()

Definition at line 551 of file qlocalserver.cpp.

◆ setMaxPendingConnections()

void QLocalServer::setMaxPendingConnections ( int numConnections)

Sets the maximum number of pending accepted connections to numConnections.

QLocalServer will accept no more than numConnections incoming connections before nextPendingConnection() is called.

Note: Even though QLocalServer will stop accepting new connections after it has reached its maximum number of pending connections, the operating system may still keep them in queue which will result in clients signaling that it is connected.

See also
maxPendingConnections(), hasPendingConnections()

Definition at line 503 of file qlocalserver.cpp.

◆ setSocketOptions()

void QLocalServer::setSocketOptions ( SocketOptions options)

Definition at line 146 of file qlocalserver.cpp.

◆ socketDescriptor()

qintptr QLocalServer::socketDescriptor ( ) const
Since
5.10 Returns the native socket descriptor the server uses to listen for incoming instructions, or -1 if the server is not listening.

The type of the descriptor depends on the platform: \list

  • On Windows, the returned value is a \l{Winsock 2 Socket Handle}.
  • On all other UNIX-like operating systems, the type is a file descriptor representing a listening socket. \endlist
See also
listen()

Definition at line 191 of file qlocalserver.cpp.

◆ socketOptions()

QLocalServer::SocketOptions QLocalServer::socketOptions ( ) const
Since
5.0 Returns the socket options set on the socket.
See also
setSocketOptions()

Definition at line 159 of file qlocalserver.cpp.

◆ waitForNewConnection()

bool QLocalServer::waitForNewConnection ( int msec = 0,
bool * timedOut = nullptr )

Waits for at most msec milliseconds or until an incoming connection is available.

Returns true if a connection is available; otherwise returns false. If the operation timed out and timedOut is not \nullptr, *timedOut will be set to true.

This is a blocking function call. Its use is ill-advised in a single-threaded GUI application, since the whole application will stop responding until the function returns. waitForNewConnection() is mostly useful when there is no event loop available.

The non-blocking alternative is to connect to the newConnection() signal.

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

See also
hasPendingConnections(), nextPendingConnection()

Definition at line 526 of file qlocalserver.cpp.

Property Documentation

◆ socketOptions

SocketOptions QLocalServer::socketOptions
readwrite

the socket options that control how the socket operates.

Since
5.0

For example, the socket may restrict access to what user ids can connect to the socket.

These options must be set before listen() is called.

In some cases, such as with Unix domain sockets on Linux, the access to the socket will be determined by file system permissions, and are created based on the umask. Setting the access flags will override this and will restrict or permit access as specified.

Other Unix-based operating systems, such as \macos, do not honor file permissions for Unix domain sockets and by default have WorldAccess and these permission flags will have no effect.

On Windows, UserAccessOption is sufficient to allow a non elevated process to connect to a local server created by an elevated process run by the same user. GroupAccessOption refers to the primary group of the process (see TokenPrimaryGroup in the Windows documentation). OtherAccessOption refers to the well known "Everyone" group.

On Linux platforms it is possible to create a socket in the abstract namespace, which is independent of the filesystem. Using this kind of socket implies ignoring permission options. On other platforms AbstractNamespaceOption is equivalent to WorldAccessOption.

By default none of the flags are set, access permissions are the platform default.

See also
listen()

Definition at line 23 of file qlocalserver.h.


The documentation for this class was generated from the following files: