Qt
Internal/Contributor docs for the Qt SDK. <b>Note:</b> These are NOT official API docs; those are found <a href='https://doc.qt.io/'>here</a>.
Loading...
Searching...
No Matches
QAbstractSocket Class Reference

The QAbstractSocket class provides the base functionality common to all socket types. More...

#include <qabstractsocket.h>

+ Inheritance diagram for QAbstractSocket:
+ Collaboration diagram for QAbstractSocket:

Public Types

enum  SocketType { TcpSocket , UdpSocket , SctpSocket , UnknownSocketType = -1 }
 This enum describes the transport layer protocol. More...
 
enum  SocketError {
  ConnectionRefusedError , RemoteHostClosedError , HostNotFoundError , SocketAccessError ,
  SocketResourceError , SocketTimeoutError , DatagramTooLargeError , NetworkError ,
  AddressInUseError , SocketAddressNotAvailableError , UnsupportedSocketOperationError , UnfinishedSocketOperationError ,
  ProxyAuthenticationRequiredError , SslHandshakeFailedError , ProxyConnectionRefusedError , ProxyConnectionClosedError ,
  ProxyConnectionTimeoutError , ProxyNotFoundError , ProxyProtocolError , OperationError ,
  SslInternalError , SslInvalidUserDataError , TemporaryError , UnknownSocketError = -1
}
 This enum describes the socket errors that can occur. More...
 
enum  SocketState {
  UnconnectedState , HostLookupState , ConnectingState , ConnectedState ,
  BoundState , ListeningState , ClosingState
}
 This enum describes the different states in which a socket can be. More...
 
enum  SocketOption {
  LowDelayOption , KeepAliveOption , MulticastTtlOption , MulticastLoopbackOption ,
  TypeOfServiceOption , SendBufferSizeSocketOption , ReceiveBufferSizeSocketOption , PathMtuSocketOption
}
 
enum  BindFlag { DefaultForPlatform = 0x0 , ShareAddress = 0x1 , DontShareAddress = 0x2 , ReuseAddressHint = 0x4 }
 
enum  PauseMode { PauseNever = 0x0 , PauseOnSslErrors = 0x1 }
 
using NetworkLayerProtocol = QHostAddress::NetworkLayerProtocol
 
- Public Types inherited from QIODeviceBase
enum  OpenModeFlag {
  NotOpen = 0x0000 , ReadOnly = 0x0001 , WriteOnly = 0x0002 , ReadWrite = ReadOnly | WriteOnly ,
  Append = 0x0004 , Truncate = 0x0008 , Text = 0x0010 , Unbuffered = 0x0020 ,
  NewOnly = 0x0040 , ExistingOnly = 0x0080
}
 This enum is used with QIODevice::open() to describe the mode in which a device is opened. More...
 

Signals

void hostFound ()
 This signal is emitted after connectToHost() has been called and the host lookup has succeeded.
 
void connected ()
 This signal is emitted after connectToHost() has been called and a connection has been successfully established.
 
void disconnected ()
 This signal is emitted when the socket has been disconnected.
 
void stateChanged (QAbstractSocket::SocketState)
 This signal is emitted whenever QAbstractSocket's state changes.
 
void errorOccurred (QAbstractSocket::SocketError)
 
void proxyAuthenticationRequired (const QNetworkProxy &proxy, QAuthenticator *authenticator)
 
- Signals inherited from QIODevice
void readyRead ()
 This signal is emitted once every time new data is available for reading from the device's current read channel.
 
void channelReadyRead (int channel)
 
void bytesWritten (qint64 bytes)
 This signal is emitted every time a payload of data has been written to the device's current write channel.
 
void channelBytesWritten (int channel, qint64 bytes)
 
void aboutToClose ()
 This signal is emitted when the device is about to close.
 
void readChannelFinished ()
 
- 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

 QAbstractSocket (SocketType socketType, QObject *parent)
 Creates a new abstract socket of type socketType.
 
virtual ~QAbstractSocket ()
 Destroys the socket.
 
virtual void resume ()
 
PauseModes pauseMode () const
 
void setPauseMode (PauseModes pauseMode)
 
virtual bool bind (const QHostAddress &address, quint16 port=0, BindMode mode=DefaultForPlatform)
 
bool bind (QHostAddress::SpecialAddress addr, quint16 port=0, BindMode mode=DefaultForPlatform)
 
bool bind (quint16 port=0, BindMode mode=DefaultForPlatform)
 
virtual void connectToHost (const QString &hostName, quint16 port, OpenMode mode=ReadWrite, NetworkLayerProtocol protocol=AnyIPProtocol)
 Attempts to make a connection to hostName on the given port.
 
void connectToHost (const QHostAddress &address, quint16 port, OpenMode mode=ReadWrite)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Attempts to make a connection to address on port port.
 
virtual void disconnectFromHost ()
 Attempts to close the socket.
 
bool isValid () const
 Returns true if the socket is valid and ready for use; otherwise returns false.
 
qint64 bytesAvailable () const override
 Returns the number of incoming bytes that are waiting to be read.
 
qint64 bytesToWrite () const override
 Returns the number of bytes that are waiting to be written.
 
quint16 localPort () const
 Returns the host port number (in native byte order) of the local socket if available; otherwise returns 0.
 
QHostAddress localAddress () const
 Returns the host address of the local socket if available; otherwise returns QHostAddress::Null.
 
quint16 peerPort () const
 Returns the port of the connected peer if the socket is in ConnectedState; otherwise returns 0.
 
QHostAddress peerAddress () const
 Returns the address of the connected peer if the socket is in ConnectedState; otherwise returns QHostAddress::Null.
 
QString peerName () const
 Returns the name of the peer as specified by connectToHost(), or an empty QString if connectToHost() has not been called.
 
qint64 readBufferSize () const
 Returns the size of the internal read buffer.
 
virtual void setReadBufferSize (qint64 size)
 Sets the size of QAbstractSocket's internal read buffer to be size bytes.
 
void abort ()
 Aborts the current connection and resets the socket.
 
virtual qintptr socketDescriptor () const
 Returns the native socket descriptor of the QAbstractSocket object if this is available; otherwise returns -1.
 
virtual bool setSocketDescriptor (qintptr socketDescriptor, SocketState state=ConnectedState, OpenMode openMode=ReadWrite)
 Initializes QAbstractSocket with the native socket descriptor socketDescriptor.
 
virtual void setSocketOption (QAbstractSocket::SocketOption option, const QVariant &value)
 
virtual QVariant socketOption (QAbstractSocket::SocketOption option)
 
SocketType socketType () const
 Returns the socket type (TCP, UDP, or other).
 
SocketState state () const
 Returns the state of the socket.
 
SocketError error () const
 Returns the type of error that last occurred.
 
void close () override
 Closes the I/O device for the socket and calls disconnectFromHost() to close the socket's connection.
 
bool isSequential () const override
 \reimp
 
bool flush ()
 This function writes as much as possible from the internal write buffer to the underlying network socket, without blocking.
 
virtual bool waitForConnected (int msecs=30000)
 Waits until the socket is connected, up to msecs milliseconds.
 
bool waitForReadyRead (int msecs=30000) override
 This function blocks until new data is available for reading and the \l{QIODevice::}{readyRead()} signal has been emitted.
 
bool waitForBytesWritten (int msecs=30000) override
 \reimp
 
virtual bool waitForDisconnected (int msecs=30000)
 Waits until the socket has disconnected, up to msecs milliseconds.
 
void setProxy (const QNetworkProxy &networkProxy)
 
QNetworkProxy proxy () const
 
QString protocolTag () const
 
void setProtocolTag (const QString &tag)
 
- Public Member Functions inherited from QIODevice
 QIODevice ()
 Constructs a QIODevice object.
 
 QIODevice (QObject *parent)
 Constructs a QIODevice object with the given parent.
 
virtual ~QIODevice ()
 The destructor is virtual, and QIODevice is an abstract base class.
 
QIODeviceBase::OpenMode openMode () const
 Returns the mode in which the device has been opened; i.e.
 
void setTextModeEnabled (bool enabled)
 If enabled is true, this function sets the \l Text flag on the device; otherwise the \l Text flag is removed.
 
bool isTextModeEnabled () const
 Returns true if the \l Text flag is enabled; otherwise returns false.
 
bool isOpen () const
 Returns true if the device is open; otherwise returns false.
 
bool isReadable () const
 Returns true if data can be read from the device; otherwise returns false.
 
bool isWritable () const
 Returns true if data can be written to the device; otherwise returns false.
 
int readChannelCount () const
 
int writeChannelCount () const
 
int currentReadChannel () const
 
void setCurrentReadChannel (int channel)
 
int currentWriteChannel () const
 
void setCurrentWriteChannel (int channel)
 
virtual bool open (QIODeviceBase::OpenMode mode)
 Opens the device and sets its OpenMode to mode.
 
virtual qint64 pos () const
 For random-access devices, this function returns the position that data is written to or read from.
 
virtual qint64 size () const
 For open random-access devices, this function returns the size of the device.
 
virtual bool seek (qint64 pos)
 For random-access devices, this function sets the current position to pos, returning true on success, or false if an error occurred.
 
virtual bool atEnd () const
 Returns true if the current read and write position is at the end of the device (i.e.
 
virtual bool reset ()
 Seeks to the start of input for random-access devices.
 
qint64 read (char *data, qint64 maxlen)
 Reads at most maxSize bytes from the device into data, and returns the number of bytes read.
 
QByteArray read (qint64 maxlen)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Reads at most maxSize bytes from the device, and returns the data read as a QByteArray.
 
QByteArray readAll ()
 Reads all remaining data from the device, and returns it as a byte array.
 
qint64 readLine (char *data, qint64 maxlen)
 This function reads a line of ASCII characters from the device, up to a maximum of maxSize - 1 bytes, stores the characters in data, and returns the number of bytes read.
 
QByteArray readLine (qint64 maxlen=0)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Reads a line from the device, but no more than maxSize characters, and returns the result as a byte array.
 
virtual bool canReadLine () const
 Returns true if a complete line of data can be read from the device; otherwise returns false.
 
void startTransaction ()
 
void commitTransaction ()
 
void rollbackTransaction ()
 
bool isTransactionStarted () const
 
qint64 write (const char *data, qint64 len)
 Writes at most maxSize bytes of data from data to the device.
 
qint64 write (const char *data)
 
qint64 write (const QByteArray &data)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Writes the content of data to the device.
 
qint64 peek (char *data, qint64 maxlen)
 
QByteArray peek (qint64 maxlen)
 
qint64 skip (qint64 maxSize)
 
void ungetChar (char c)
 Puts the character c back into the device, and decrements the current position unless the position is 0.
 
bool putChar (char c)
 Writes the character c to the device.
 
bool getChar (char *c)
 Reads one character from the device and stores it in c.
 
QString errorString () const
 Returns a human-readable description of the last device error that occurred.
 
- 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 Attributes

static constexpr auto IPv4Protocol = QHostAddress::IPv4Protocol
 
static constexpr auto IPv6Protocol = QHostAddress::IPv6Protocol
 
static constexpr auto AnyIPProtocol = QHostAddress::AnyIPProtocol
 
static constexpr auto UnknownNetworkLayerProtocol = QHostAddress::UnknownNetworkLayerProtocol
 

Protected Member Functions

qint64 readData (char *data, qint64 maxlen) override
 \reimp
 
qint64 readLineData (char *data, qint64 maxlen) override
 \reimp
 
qint64 skipData (qint64 maxSize) override
 \reimp
 
qint64 writeData (const char *data, qint64 len) override
 \reimp
 
void setSocketState (SocketState state)
 Sets the state of the socket to state.
 
void setSocketError (SocketError socketError)
 Sets the type of error that last occurred to socketError.
 
void setLocalPort (quint16 port)
 
void setLocalAddress (const QHostAddress &address)
 
void setPeerPort (quint16 port)
 
void setPeerAddress (const QHostAddress &address)
 
void setPeerName (const QString &name)
 
 QAbstractSocket (SocketType socketType, QAbstractSocketPrivate &dd, QObject *parent=nullptr)
 
- Protected Member Functions inherited from QIODevice
 QIODevice (QIODevicePrivate &dd, QObject *parent=nullptr)
 
void setOpenMode (QIODeviceBase::OpenMode openMode)
 Sets the OpenMode of the device to openMode.
 
void setErrorString (const QString &errorString)
 Sets the human readable description of the last device error that occurred to str.
 
- 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)
 
- Protected Member Functions inherited from QIODeviceBase
 ~QIODeviceBase ()=default
 

Additional Inherited Members

- Public Slots inherited from QObject
void deleteLater ()
 \threadsafe
 
- 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 Attributes inherited from QObject
QScopedPointer< QObjectDatad_ptr
 
- Properties inherited from QObject
QString objectName
 the name of this object
 

Detailed Description

The QAbstractSocket class provides the base functionality common to all socket types.

\reentrant

\inmodule QtNetwork

QAbstractSocket is the base class for QTcpSocket and QUdpSocket and contains all common functionality of these two classes. If you need a socket, you have two options:

\list

TCP (Transmission Control Protocol) is a reliable, stream-oriented, connection-oriented transport protocol. UDP (User Datagram Protocol) is an unreliable, datagram-oriented, connectionless protocol. In practice, this means that TCP is better suited for continuous transmission of data, whereas the more lightweight UDP can be used when reliability isn't important.

QAbstractSocket's API unifies most of the differences between the two protocols. For example, although UDP is connectionless, connectToHost() establishes a virtual connection for UDP sockets, enabling you to use QAbstractSocket in more or less the same way regardless of the underlying protocol. Internally, QAbstractSocket remembers the address and port passed to connectToHost(), and functions like read() and write() use these values.

At any time, QAbstractSocket has a state (returned by state()). The initial state is UnconnectedState. After calling connectToHost(), the socket first enters HostLookupState. If the host is found, QAbstractSocket enters ConnectingState and emits the hostFound() signal. When the connection has been established, it enters ConnectedState and emits connected(). If an error occurs at any stage, errorOccurred() is emitted. Whenever the state changes, stateChanged() is emitted. For convenience, isValid() returns true if the socket is ready for reading and writing, but note that the socket's state must be ConnectedState before reading and writing can occur.

Read or write data by calling read() or write(), or use the convenience functions readLine() and readAll(). QAbstractSocket also inherits getChar(), putChar(), and ungetChar() from QIODevice, which work on single bytes. The bytesWritten() signal is emitted when data has been written to the socket. Note that Qt does not limit the write buffer size. You can monitor its size by listening to this signal.

The readyRead() signal is emitted every time a new chunk of data has arrived. bytesAvailable() then returns the number of bytes that are available for reading. Typically, you would connect the readyRead() signal to a slot and read all available data there. If you don't read all the data at once, the remaining data will still be available later, and any new incoming data will be appended to QAbstractSocket's internal read buffer. To limit the size of the read buffer, call setReadBufferSize().

To close the socket, call disconnectFromHost(). QAbstractSocket enters QAbstractSocket::ClosingState. After all pending data has been written to the socket, QAbstractSocket actually closes the socket, enters QAbstractSocket::UnconnectedState, and emits disconnected(). If you want to abort a connection immediately, discarding all pending data, call abort() instead. If the remote host closes the connection, QAbstractSocket will emit errorOccurred(QAbstractSocket::RemoteHostClosedError), during which the socket state will still be ConnectedState, and then the disconnected() signal will be emitted.

The port and address of the connected peer is fetched by calling peerPort() and peerAddress(). peerName() returns the host name of the peer, as passed to connectToHost(). localPort() and localAddress() return the port and address of the local socket.

QAbstractSocket provides a set of functions that suspend the calling thread until certain signals are emitted. These functions can be used to implement blocking sockets:

\list

We show an example:

int numRead = 0, numReadTotal = 0;
char buffer[50];
numRead = socket.read(buffer, 50);
// do whatever with array
numReadTotal += numRead;
if (numRead == 0 && !socket.waitForReadyRead())
break;
}

If \l{QIODevice::}{waitForReadyRead()} returns false, the connection has been closed or an error has occurred.

Programming with a blocking socket is radically different from programming with a non-blocking socket. A blocking socket doesn't require an event loop and typically leads to simpler code. However, in a GUI application, blocking sockets should only be used in non-GUI threads, to avoid freezing the user interface. See the \l fortuneclient and \l blockingfortuneclient examples for an overview of both approaches.

Note
We discourage the use of the blocking functions together with signals. One of the two possibilities should be used.

QAbstractSocket can be used with QTextStream and QDataStream's stream operators (operator<<() and operator>>()). There is one issue to be aware of, though: You must make sure that enough data is available before attempting to read it using operator>>().

See also
QNetworkAccessManager, QTcpServer

Definition at line 30 of file qabstractsocket.h.

Member Typedef Documentation

◆ NetworkLayerProtocol

Member Enumeration Documentation

◆ BindFlag

Since
5.0

This enum describes the different flags you can pass to modify the behavior of QAbstractSocket::bind().

\value ShareAddress Allow other services to bind to the same address and port. This is useful when multiple processes share the load of a single service by listening to the same address and port (e.g., a web server with several pre-forked listeners can greatly improve response time). However, because any service is allowed to rebind, this option is subject to certain security considerations. Note that by combining this option with ReuseAddressHint, you will also allow your service to rebind an existing shared address. On Unix, this is equivalent to the SO_REUSEADDR socket option. On Windows, this is the default behavior, so this option is ignored.

\value DontShareAddress Bind the address and port exclusively, so that no other services are allowed to rebind. By passing this option to QAbstractSocket::bind(), you are guaranteed that on success, your service is the only one that listens to the address and port. No services are allowed to rebind, even if they pass ReuseAddressHint. This option provides more security than ShareAddress, but on certain operating systems, it requires you to run the server with administrator privileges. On Unix and \macos, not sharing is the default behavior for binding an address and port, so this option is ignored. On Windows, this option uses the SO_EXCLUSIVEADDRUSE socket option.

\value ReuseAddressHint Provides a hint to QAbstractSocket that it should try to rebind the service even if the address and port are already bound by another socket. On Windows and Unix, this is equivalent to the SO_REUSEADDR socket option.

\value DefaultForPlatform The default option for the current platform. On Unix and \macos, this is equivalent to (DontShareAddress

  • ReuseAddressHint), and on Windows, it is equivalent to ShareAddress.
Enumerator
DefaultForPlatform 
ShareAddress 
DontShareAddress 
ReuseAddressHint 

Definition at line 110 of file qabstractsocket.h.

◆ PauseMode

Since
5.0

This enum describes the behavior of when the socket should hold back with continuing data transfer. The only notification currently supported is QSslSocket::sslErrors().

\value PauseNever Do not pause data transfer on the socket. This is the default and matches the behavior of Qt 4. \value PauseOnSslErrors Pause data transfer on the socket upon receiving an SSL error notification. I.E. QSslSocket::sslErrors().

Enumerator
PauseNever 
PauseOnSslErrors 

Definition at line 117 of file qabstractsocket.h.

◆ SocketError

This enum describes the socket errors that can occur.

\value ConnectionRefusedError The connection was refused by the peer (or timed out). \value RemoteHostClosedError The remote host closed the connection. Note that the client socket (i.e., this socket) will be closed after the remote close notification has been sent. \value HostNotFoundError The host address was not found. \value SocketAccessError The socket operation failed because the application lacked the required privileges. \value SocketResourceError The local system ran out of resources (e.g., too many sockets). \value SocketTimeoutError The socket operation timed out. \value DatagramTooLargeError The datagram was larger than the operating system's limit (which can be as low as 8192 bytes). \value NetworkError An error occurred with the network (e.g., the network cable was accidentally plugged out). \value AddressInUseError The address specified to QAbstractSocket::bind() is already in use and was set to be exclusive. \value SocketAddressNotAvailableError The address specified to QAbstractSocket::bind() does not belong to the host. \value UnsupportedSocketOperationError The requested socket operation is not supported by the local operating system (e.g., lack of IPv6 support). \value ProxyAuthenticationRequiredError The socket is using a proxy, and the proxy requires authentication. \value SslHandshakeFailedError The SSL/TLS handshake failed, so the connection was closed (only used in QSslSocket) \value UnfinishedSocketOperationError Used by QAbstractSocketEngine only, The last operation attempted has not finished yet (still in progress in the background). \value ProxyConnectionRefusedError Could not contact the proxy server because the connection to that server was denied \value ProxyConnectionClosedError The connection to the proxy server was closed unexpectedly (before the connection to the final peer was established) \value ProxyConnectionTimeoutError The connection to the proxy server timed out or the proxy server stopped responding in the authentication phase. \value ProxyNotFoundError The proxy address set with setProxy() (or the application proxy) was not found. \value ProxyProtocolError The connection negotiation with the proxy server failed, because the response from the proxy server could not be understood. \value OperationError An operation was attempted while the socket was in a state that did not permit it. \value SslInternalError The SSL library being used reported an internal error. This is probably the result of a bad installation or misconfiguration of the library. \value SslInvalidUserDataError Invalid data (certificate, key, cypher, etc.) was provided and its use resulted in an error in the SSL library. \value TemporaryError A temporary error occurred (e.g., operation would block and socket is non-blocking).

\value UnknownSocketError An unidentified error occurred.

See also
QAbstractSocket::error()
QAbstractSocket::errorOccurred()
Enumerator
ConnectionRefusedError 
RemoteHostClosedError 
HostNotFoundError 
SocketAccessError 
SocketResourceError 
SocketTimeoutError 
DatagramTooLargeError 
NetworkError 
AddressInUseError 
SocketAddressNotAvailableError 
UnsupportedSocketOperationError 
UnfinishedSocketOperationError 
ProxyAuthenticationRequiredError 
SslHandshakeFailedError 
ProxyConnectionRefusedError 
ProxyConnectionClosedError 
ProxyConnectionTimeoutError 
ProxyNotFoundError 
ProxyProtocolError 
OperationError 
SslInternalError 
SslInvalidUserDataError 
TemporaryError 
UnknownSocketError 

Definition at line 61 of file qabstractsocket.h.

◆ SocketOption

Since
4.6

This enum represents the options that can be set on a socket. If desired, they can be set after having received the connected() signal from the socket or after having received a new socket from a QTcpServer.

\value LowDelayOption Try to optimize the socket for low latency. For a QTcpSocket this would set the TCP_NODELAY option and disable Nagle's algorithm. Set this to 1 to enable.

\value KeepAliveOption Set this to 1 to enable the SO_KEEPALIVE socket option

\value MulticastTtlOption Set this to an integer value to set IP_MULTICAST_TTL (TTL for multicast datagrams) socket option.

\value MulticastLoopbackOption Set this to 1 to enable the IP_MULTICAST_LOOP (multicast loopback) socket option.

\value TypeOfServiceOption This option is not supported on Windows. This maps to the IP_TOS socket option. For possible values, see table below.

\value SendBufferSizeSocketOption Sets the socket send buffer size in bytes at the OS level. This maps to the SO_SNDBUF socket option. This option does not affect the QIODevice or QAbstractSocket buffers. This enum value has been introduced in Qt 5.3.

\value ReceiveBufferSizeSocketOption Sets the socket receive buffer size in bytes at the OS level. This maps to the SO_RCVBUF socket option. This option does not affect the QIODevice or QAbstractSocket buffers (see \l{QAbstractSocket::}{setReadBufferSize()}). This enum value has been introduced in Qt 5.3.

\value PathMtuSocketOption Retrieves the Path Maximum Transmission Unit (PMTU) value currently known by the IP stack, if any. Some IP stacks also allow setting the MTU for transmission. This enum value was introduced in Qt 5.11.

Possible values for {TypeOfServiceOption} are:

\table \header

  • Value
  • Description \row
  • 224
  • Network control \row
  • 192
  • Internetwork control \row
  • 160
  • CRITIC/ECP \row
  • 128
  • Flash override \row
  • 96
  • Flash \row
  • 64
  • Immediate \row
  • 32
  • Priority \row
  • 0
  • Routine \endtable
See also
QAbstractSocket::setSocketOption(), QAbstractSocket::socketOption()
Enumerator
LowDelayOption 
KeepAliveOption 
MulticastTtlOption 
MulticastLoopbackOption 
TypeOfServiceOption 
SendBufferSizeSocketOption 
ReceiveBufferSizeSocketOption 
PathMtuSocketOption 

Definition at line 99 of file qabstractsocket.h.

◆ SocketState

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

\value UnconnectedState The socket is not connected. \value HostLookupState The socket is performing a host name lookup. \value ConnectingState The socket has started establishing a connection. \value ConnectedState A connection is established. \value BoundState The socket is bound to an address and port. \value ClosingState The socket is about to close (data may still be waiting to be written). \value ListeningState For internal use only.

See also
QAbstractSocket::state()
Enumerator
UnconnectedState 
HostLookupState 
ConnectingState 
ConnectedState 
BoundState 
ListeningState 
ClosingState 

Definition at line 89 of file qabstractsocket.h.

◆ SocketType

This enum describes the transport layer protocol.

\value TcpSocket TCP \value UdpSocket UDP \value SctpSocket SCTP \value UnknownSocketType Other than TCP, UDP and SCTP

See also
QAbstractSocket::socketType()
Enumerator
TcpSocket 
UdpSocket 
SctpSocket 
UnknownSocketType 

Definition at line 36 of file qabstractsocket.h.

Constructor & Destructor Documentation

◆ QAbstractSocket() [1/2]

QAbstractSocket::QAbstractSocket ( SocketType socketType,
QObject * parent )

Creates a new abstract socket of type socketType.

The parent argument is passed to QObject's constructor.

See also
socketType(), QTcpSocket, QUdpSocket

Definition at line 1408 of file qabstractsocket.cpp.

◆ ~QAbstractSocket()

QAbstractSocket::~QAbstractSocket ( )
virtual

Destroys the socket.

Definition at line 1416 of file qabstractsocket.cpp.

References abort(), d, qDebug, and UnconnectedState.

+ Here is the call graph for this function:

◆ QAbstractSocket() [2/2]

QAbstractSocket::QAbstractSocket ( SocketType socketType,
QAbstractSocketPrivate & dd,
QObject * parent = nullptr )
protected

Constructs a new abstract socket of type socketType. The parent argument is passed to QObject's constructor.

Definition at line 1389 of file qabstractsocket.cpp.

References d, QObject::parent(), qDebug, SctpSocket, socketType(), TcpSocket, and UdpSocket.

+ Here is the call graph for this function:

Member Function Documentation

◆ abort()

void QAbstractSocket::abort ( )

Aborts the current connection and resets the socket.

Unlike disconnectFromHost(), this function immediately closes the socket, discarding any pending data in the write buffer.

See also
disconnectFromHost(), close()

Definition at line 2345 of file qabstractsocket.cpp.

References close(), d, and qDebug.

Referenced by ~QAbstractSocket(), and QHttpNetworkConnectionChannel::abort().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ bind() [1/3]

bool QAbstractSocket::bind ( const QHostAddress & address,
quint16 port = 0,
BindMode mode = DefaultForPlatform )
virtual
Since
5.0

Binds to address on port port, using the BindMode mode.

For UDP sockets, after binding, the signal QUdpSocket::readyRead() is emitted whenever a UDP datagram arrives on the specified address and port. Thus, this function is useful to write UDP servers.

For TCP sockets, this function may be used to specify which interface to use for an outgoing connection, which is useful in case of multiple network interfaces.

By default, the socket is bound using the DefaultForPlatform BindMode. If a port is not specified, a random port is chosen.

On success, the function returns true and the socket enters BoundState; otherwise it returns false.

Definition at line 1495 of file qabstractsocket.cpp.

References d.

Referenced by QSslSocketPrivate::bind(), DtlsServer::listen(), QUdpSocket::writeDatagram(), and QUdpSocket::writeDatagram().

+ Here is the caller graph for this function:

◆ bind() [2/3]

bool QAbstractSocket::bind ( QHostAddress::SpecialAddress addr,
quint16 port = 0,
BindMode mode = DefaultForPlatform )
inline
Since
6.2 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Binds to the special address addr on port port, using the BindMode mode.

By default, the socket is bound using the DefaultForPlatform BindMode. If a port is not specified, a random port is chosen.

Definition at line 133 of file qabstractsocket.h.

References bind().

+ Here is the call graph for this function:

◆ bind() [3/3]

bool QAbstractSocket::bind ( quint16 port = 0,
BindMode mode = DefaultForPlatform )
inline
Since
5.0 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Binds to QHostAddress:Any on port port, using the BindMode mode.

By default, the socket is bound using the DefaultForPlatform BindMode. If a port is not specified, a random port is chosen.

Definition at line 135 of file qabstractsocket.h.

References QHostAddress::Any, and bind().

+ Here is the call graph for this function:

◆ bytesAvailable()

◆ bytesToWrite()

qint64 QAbstractSocket::bytesToWrite ( ) const
overridevirtual

Returns the number of bytes that are waiting to be written.

The bytes are written when control goes back to the event loop or when flush() is called.

See also
bytesAvailable(), flush()

Reimplemented from QIODevice.

Reimplemented in QSslSocket.

Definition at line 1741 of file qabstractsocket.cpp.

References QIODevice::bytesToWrite(), and qDebug.

Referenced by QTcpServerConnection::disconnect().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ close()

void QAbstractSocket::close ( )
overridevirtual

Closes the I/O device for the socket and calls disconnectFromHost() to close the socket's connection.

See QIODevice::close() for a description of the actions that occur when an I/O device is closed.

See also
abort()

Reimplemented from QIODevice.

Reimplemented in QSctpSocket, and QSslSocket.

Definition at line 2593 of file qabstractsocket.cpp.

References QIODevice::close(), d, disconnectFromHost(), qDebug, and UnconnectedState.

Referenced by QHttpNetworkConnectionPrivate::~QHttpNetworkConnectionPrivate(), abort(), QHttpNetworkConnectionChannel::close(), QSocks5PasswordAuthenticator::continueAuthenticate(), QCtfServer::run(), waitForBytesWritten(), waitForDisconnected(), and waitForReadyRead().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ connected

void QAbstractSocket::connected ( )
signal

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

Note
On some operating systems the connected() signal may be directly emitted from the connectToHost() call for connections to the localhost.
See also
connectToHost(), disconnected()

Referenced by QQmlDebugConnection::connectToHost(), and QHttpNetworkConnectionChannel::init().

+ Here is the caller graph for this function:

◆ connectToHost() [1/2]

void QAbstractSocket::connectToHost ( const QHostAddress & address,
quint16 port,
OpenMode mode = ReadWrite )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Attempts to make a connection to address on port port.

Definition at line 1724 of file qabstractsocket.cpp.

References connectToHost(), QIODevice::openMode(), and qDebug.

+ Here is the call graph for this function:

◆ connectToHost() [2/2]

void QAbstractSocket::connectToHost ( const QString & hostName,
quint16 port,
OpenMode openMode = ReadWrite,
NetworkLayerProtocol protocol = AnyIPProtocol )
virtual

Attempts to make a connection to hostName on the given port.

The protocol parameter can be used to specify which network protocol to use (eg. IPv4 or IPv6).

The socket is opened in the given openMode and first enters HostLookupState, then performs a host name lookup of hostName. If the lookup succeeds, hostFound() is emitted and QAbstractSocket enters ConnectingState. It then attempts to connect to the address or addresses returned by the lookup. Finally, if a connection is established, QAbstractSocket enters ConnectedState and emits connected().

At any point, the socket can emit errorOccurred() to signal that an error occurred.

hostName may be an IP address in string form (e.g., "43.195.83.32"), or it may be a host name (e.g., "example.com"). QAbstractSocket will do a lookup only if required. port is in native byte order.

See also
state(), peerName(), peerAddress(), peerPort(), waitForConnected()

Reimplemented in QSslSocket, and QSslSocket.

Definition at line 1623 of file qabstractsocket.cpp.

References QHostInfo::abortHostLookup(), BoundState, QString::clear(), ClosingState, ConnectedState, ConnectingState, QByteArray::constData(), d, QNetworkProxy::DefaultProxy, emit, HostLookupState, QNetworkProxy::HostNameLookupCapability, info, QIODevice::open(), QIODevice::openMode(), OperationError, qDebug, qPrintable, qt_qhostinfo_lookup(), qWarning, QHostAddress::setAddress(), QHostInfo::setAddresses(), SLOT, stateChanged(), QString::toLatin1(), tr, QIODeviceBase::Unbuffered, UnconnectedState, UnknownSocketError, and UnsupportedSocketOperationError.

Referenced by connectToHost(), QQmlDebugConnection::connectToHost(), QHttpNetworkConnectionChannel::ensureConnection(), and test_tcpwait().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ disconnected

void QAbstractSocket::disconnected ( )
signal

This signal is emitted when the socket has been disconnected.

Warning
If you need to delete the sender() of this signal in a slot connected to it, use the \l{QObject::deleteLater()}{deleteLater()} function.
See also
connectToHost(), disconnectFromHost(), abort()

Referenced by QQmlDebugConnection::connectToHost(), disconnectFromHost(), QHttpNetworkConnectionChannel::init(), and QCtfServer::run().

+ Here is the caller graph for this function:

◆ disconnectFromHost()

void QAbstractSocket::disconnectFromHost ( )
virtual

Attempts to close the socket.

If there is pending data waiting to be written, QAbstractSocket will enter ClosingState and wait until all data has been written. Eventually, it will enter UnconnectedState and emit the disconnected() signal.

See also
connectToHost()

Reimplemented in QSctpSocket, and QSslSocket.

Definition at line 2612 of file qabstractsocket.cpp.

References QHostInfo::abortHostLookup(), ClosingState, ConnectedState, ConnectingState, d, disconnected(), emit, HostLookupState, qDebug, QIODevice::readChannelFinished(), stateChanged(), and UnconnectedState.

Referenced by QSslSocketPrivate::_q_resumeImplementation(), QSslServerPrivate::checkClientHelloAndContinue(), close(), QSctpSocket::disconnectFromHost(), QTlsPrivate::TlsCryptographSchannel::disconnectFromHost(), QTlsPrivate::TlsCryptographSecureTransport::disconnectFromHost(), QSslServerPrivate::handleHandshakeTimedOut(), and waitForConnected().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ error()

QAbstractSocket::SocketError QAbstractSocket::error ( ) const

Returns the type of error that last occurred.

See also
state(), errorString()

Definition at line 2787 of file qabstractsocket.cpp.

Referenced by QSslSocketPrivate::_q_errorSlot(), QLocalUnixSocket::setSocketError(), QTlsPrivate::TlsCryptographSchannel::transmit(), and QDtlsPrivateOpenSSL::writeDatagramEncrypted().

+ Here is the caller graph for this function:

◆ errorOccurred

void QAbstractSocket::errorOccurred ( QAbstractSocket::SocketError socketError)
signal
Since
5.15

This signal is emitted after an error occurred. The socketError parameter describes the type of error that occurred.

When this signal is emitted, the socket may not be ready for a reconnect attempt. In that case, attempts to reconnect should be done from the event loop. For example, use QChronoTimer::singleShot() with 0ns as the timeout.

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

See also
error(), errorString(), {Creating Custom Qt Types}

Referenced by QQmlDebugConnection::connectToHost(), QSslServer::incomingConnection(), and QHttpNetworkConnectionChannel::init().

+ Here is the caller graph for this function:

◆ flush()

bool QAbstractSocket::flush ( )

This function writes as much as possible from the internal write buffer to the underlying network socket, without blocking.

If any data was written, this function returns true; otherwise false is returned.

Call this function if you need QAbstractSocket 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 QAbstractSocket 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(), waitForBytesWritten()

Definition at line 2377 of file qabstractsocket.cpp.

Referenced by QSslSocket::close(), QQmlDebugConnectionPrivate::flush(), QSslSocketPrivate::flush(), QTcpServerConnection::flush(), and QRfbRawEncoder::write().

+ Here is the caller graph for this function:

◆ hostFound

void QAbstractSocket::hostFound ( )
signal

This signal is emitted after connectToHost() has been called and the host lookup has succeeded.

Note
Since Qt 4.6.3 QAbstractSocket may emit hostFound() directly from the connectToHost() call since a DNS result could have been cached.
See also
connected()

◆ isSequential()

bool QAbstractSocket::isSequential ( ) const
overridevirtual

\reimp

Reimplemented from QIODevice.

Definition at line 2358 of file qabstractsocket.cpp.

◆ isValid()

bool QAbstractSocket::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()

Definition at line 1595 of file qabstractsocket.cpp.

References QIODevice::isOpen().

Referenced by ServerAcceptanceThread::javaNewSocket(), QBluetoothServer::nextPendingConnection(), QUdpSocket::setMulticastInterface(), and QTlsPrivate::TlsCryptographSchannel::transmit().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ localAddress()

QHostAddress QAbstractSocket::localAddress ( ) const

Returns the host address of the local socket if available; otherwise returns QHostAddress::Null.

This is normally the main IP address of the host, but can be QHostAddress::LocalHost (127.0.0.1) for connections to the local host.

See also
localPort(), peerAddress(), setLocalAddress()

Definition at line 1791 of file qabstractsocket.cpp.

References d.

Referenced by QHttpNetworkConnectionChannel::_q_connected(), QSslSocketPrivate::_q_connectedSlot(), and QSslSocketPrivate::bind().

+ Here is the caller graph for this function:

◆ localPort()

quint16 QAbstractSocket::localPort ( ) const

Returns the host port number (in native byte order) of the local socket if available; otherwise returns 0.

See also
localAddress(), peerPort(), setLocalPort()

Definition at line 1775 of file qabstractsocket.cpp.

References d.

Referenced by QSslSocketPrivate::_q_connectedSlot(), and QSslSocketPrivate::bind().

+ Here is the caller graph for this function:

◆ pauseMode()

QAbstractSocket::PauseModes QAbstractSocket::pauseMode ( ) const
Since
5.0

Returns the pause mode of this socket.

See also
setPauseMode(), resume()

Definition at line 1450 of file qabstractsocket.cpp.

Referenced by setPauseMode().

+ Here is the caller graph for this function:

◆ peerAddress()

QHostAddress QAbstractSocket::peerAddress ( ) const

Returns the address of the connected peer if the socket is in ConnectedState; otherwise returns QHostAddress::Null.

See also
peerName(), peerPort(), localAddress(), setPeerAddress()

Definition at line 1815 of file qabstractsocket.cpp.

References d.

Referenced by QHttpNetworkConnectionChannel::_q_connected(), and QSslSocketPrivate::_q_connectedSlot().

+ Here is the caller graph for this function:

◆ peerName()

QString QAbstractSocket::peerName ( ) const

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

See also
peerAddress(), peerPort(), setPeerName()

Definition at line 1827 of file qabstractsocket.cpp.

References d.

Referenced by QSslSocketPrivate::_q_connectedSlot().

+ Here is the caller graph for this function:

◆ peerPort()

quint16 QAbstractSocket::peerPort ( ) const

Returns the port of the connected peer if the socket is in ConnectedState; otherwise returns 0.

See also
peerAddress(), localPort(), setPeerPort()

Definition at line 1803 of file qabstractsocket.cpp.

References d.

Referenced by QSslSocketPrivate::_q_connectedSlot().

+ Here is the caller graph for this function:

◆ protocolTag()

QString QAbstractSocket::protocolTag ( ) const
Since
5.13

Returns the protocol tag for this socket. If the protocol tag is set then this is passed to QNetworkProxyQuery when this is created internally to indicate the protocol tag to be used.

See also
setProtocolTag(), QNetworkProxyQuery

Definition at line 2854 of file qabstractsocket.cpp.

References d.

◆ proxy()

QNetworkProxy QAbstractSocket::proxy ( ) const
Since
4.1

Returns the network proxy for this socket. By default QNetworkProxy::DefaultProxy is used, which means this socket will query the default proxy settings for the application.

See also
setProxy(), QNetworkProxy, QNetworkProxyFactory

Definition at line 2837 of file qabstractsocket.cpp.

References d.

Referenced by QNativeSocketEnginePrivate::checkProxy(), QSslSocket::connectToHost(), and QHttpNetworkConnectionChannel::ensureConnection().

+ Here is the caller graph for this function:

◆ proxyAuthenticationRequired

void QAbstractSocket::proxyAuthenticationRequired ( const QNetworkProxy & proxy,
QAuthenticator * authenticator )
signal
Since
4.3

This signal can be emitted when a proxy that requires authentication is used. The authenticator object can then be filled in with the required details to allow authentication and continue the connection.

Note
It is not possible to use a QueuedConnection to connect to this signal, as the connection will fail if the authenticator has not been filled in with new information when the signal returns.
See also
QAuthenticator, QNetworkProxy

Referenced by QHttpNetworkConnectionChannel::init().

+ Here is the caller graph for this function:

◆ readBufferSize()

qint64 QAbstractSocket::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(), read()

Definition at line 2709 of file qabstractsocket.cpp.

◆ readData()

qint64 QAbstractSocket::readData ( char * data,
qint64 maxlen )
overrideprotectedvirtual

\reimp

Implements QIODevice.

Reimplemented in QSctpSocket, QSslSocket, and QLocalUnixSocket.

Definition at line 2384 of file qabstractsocket.cpp.

References ConnectedState, d, qDebug, QtDebugUtils::toPrintable(), and UnconnectedState.

+ Here is the call graph for this function:

◆ readLineData()

qint64 QAbstractSocket::readLineData ( char * data,
qint64 maxlen )
overrideprotectedvirtual

\reimp

Reimplemented from QIODevice.

Reimplemented in QSctpSocket.

Definition at line 2417 of file qabstractsocket.cpp.

References QIODevice::readLineData().

+ Here is the call graph for this function:

◆ resume()

void QAbstractSocket::resume ( )
virtual
Since
5.0

Continues data transfer on the socket. This method should only be used after the socket has been set to pause upon notifications and a notification has been received. The only notification currently supported is QSslSocket::sslErrors(). Calling this method if the socket is not paused results in undefined behavior.

See also
pauseMode(), setPauseMode()

Reimplemented in QSslSocket.

Definition at line 1438 of file qabstractsocket.cpp.

References QAbstractSocketPrivate::resumeSocketNotifiers().

Referenced by QSslSocketPrivate::_q_resumeImplementation().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ setLocalAddress()

void QAbstractSocket::setLocalAddress ( const QHostAddress & address)
protected
Since
4.1

Sets the address on the local side of a connection to address.

You can call this function in a subclass of QAbstractSocket to change the return value of the localAddress() function after a connection has been established. This feature is commonly used by proxy connections for virtual connection settings.

Note that this function does not bind the local address of the socket prior to a connection (e.g., QAbstractSocket::bind()).

See also
localAddress(), setLocalPort(), setPeerAddress()

Definition at line 2522 of file qabstractsocket.cpp.

References d.

Referenced by QSslSocket::setSocketDescriptor().

+ Here is the caller graph for this function:

◆ setLocalPort()

void QAbstractSocket::setLocalPort ( quint16 port)
protected
Since
4.1

Sets the port on the local side of a connection to port.

You can call this function in a subclass of QAbstractSocket to change the return value of the localPort() function after a connection has been established. This feature is commonly used by proxy connections for virtual connection settings.

Note that this function does not bind the local port of the socket prior to a connection (e.g., QAbstractSocket::bind()).

See also
localAddress(), setLocalAddress(), setPeerPort()

Definition at line 2500 of file qabstractsocket.cpp.

References d.

Referenced by QSslSocket::setSocketDescriptor().

+ Here is the caller graph for this function:

◆ setPauseMode()

void QAbstractSocket::setPauseMode ( PauseModes pauseMode)
Since
5.0

Controls whether to pause upon receiving a notification. The pauseMode parameter specifies the conditions in which the socket should be paused. The only notification currently supported is QSslSocket::sslErrors(). If set to PauseOnSslErrors, data transfer on the socket will be paused and needs to be enabled explicitly again by calling resume(). By default this option is set to PauseNever. This option must be called before connecting to the server, otherwise it will result in undefined behavior.

See also
pauseMode(), resume()

Definition at line 1470 of file qabstractsocket.cpp.

References pauseMode().

+ Here is the call graph for this function:

◆ setPeerAddress()

void QAbstractSocket::setPeerAddress ( const QHostAddress & address)
protected
Since
4.1

Sets the address of the remote side of the connection to address.

You can call this function in a subclass of QAbstractSocket to change the return value of the peerAddress() function after a connection has been established. This feature is commonly used by proxy connections for virtual connection settings.

See also
peerAddress(), setPeerPort(), setLocalAddress()

Definition at line 2560 of file qabstractsocket.cpp.

References d.

Referenced by QSslSocket::setSocketDescriptor().

+ Here is the caller graph for this function:

◆ setPeerName()

void QAbstractSocket::setPeerName ( const QString & name)
protected
Since
4.1

Sets the host name of the remote peer to name.

You can call this function in a subclass of QAbstractSocket to change the return value of the peerName() function after a connection has been established. This feature is commonly used by proxy connections for virtual connection settings.

See also
peerName()

Definition at line 2578 of file qabstractsocket.cpp.

References d.

Referenced by QSslSocket::setSocketDescriptor().

+ Here is the caller graph for this function:

◆ setPeerPort()

void QAbstractSocket::setPeerPort ( quint16 port)
protected
Since
4.1

Sets the port of the remote side of the connection to port.

You can call this function in a subclass of QAbstractSocket to change the return value of the peerPort() function after a connection has been established. This feature is commonly used by proxy connections for virtual connection settings.

See also
peerPort(), setPeerAddress(), setLocalPort()

Definition at line 2541 of file qabstractsocket.cpp.

References d.

Referenced by QSslSocket::setSocketDescriptor().

+ Here is the caller graph for this function:

◆ setProtocolTag()

void QAbstractSocket::setProtocolTag ( const QString & tag)
Since
5.13

Sets the protocol tag for this socket to tag.

See also
protocolTag()

Definition at line 2868 of file qabstractsocket.cpp.

References d, and tag.

◆ setProxy()

void QAbstractSocket::setProxy ( const QNetworkProxy & networkProxy)
Since
4.1

Sets the explicit network proxy for this socket to networkProxy.

To disable the use of a proxy for this socket, use the QNetworkProxy::NoProxy proxy type:

The default value for the proxy is QNetworkProxy::DefaultProxy, which means the socket will use the application settings: if a proxy is set with QNetworkProxy::setApplicationProxy, it will use that; otherwise, if a factory is set with QNetworkProxyFactory::setApplicationProxyFactory, it will query that factory with type QNetworkProxyQuery::TcpSocket.

See also
proxy(), QNetworkProxy, QNetworkProxyFactory::queryProxy()

Definition at line 2822 of file qabstractsocket.cpp.

References d.

Referenced by QHttpNetworkConnectionChannel::ensureConnection(), QHttpNetworkConnectionChannel::init(), QSocks5SocketEnginePrivate::initialize(), and QHttpNetworkConnectionChannel::setProxy().

+ Here is the caller graph for this function:

◆ setReadBufferSize()

void QAbstractSocket::setReadBufferSize ( qint64 size)
virtual

Sets the size of QAbstractSocket's internal read buffer to be size bytes.

If the buffer size is limited to a certain size, QAbstractSocket 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.

Only QTcpSocket uses QAbstractSocket's internal buffer; QUdpSocket does not use any buffering at all, but rather relies on the implicit buffering provided by the operating system. Because of this, calling this function on QUdpSocket has no effect.

See also
readBufferSize(), read()

Reimplemented in QSslSocket.

Definition at line 2736 of file qabstractsocket.cpp.

References ConnectedState, d, and QIODevice::size().

Referenced by QHttpNetworkConnectionChannel::ensureConnection().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ setSocketDescriptor()

bool QAbstractSocket::setSocketDescriptor ( qintptr socketDescriptor,
SocketState socketState = ConnectedState,
OpenMode openMode = ReadWrite )
virtual

Initializes QAbstractSocket 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. Read and write buffers are cleared, discarding any pending data.

{Note:} It is not possible to initialize two abstract sockets with the same native socket descriptor.

See also
socketDescriptor()

Reimplemented in QSslSocket.

Definition at line 1864 of file qabstractsocket.cpp.

References ConnectedState, QAbstractSocketEngine::createSocketEngine(), d, emit, QIODevice::isReadable(), QIODevice::isWritable(), QIODevice::open(), QIODevice::openMode(), qMax(), socketDescriptor(), stateChanged(), tr, UnknownSocketError, and UnsupportedSocketOperationError.

Referenced by QLocalSocketPrivate::_q_connectToSocket(), QTcpServer::incomingConnection(), QSctpServer::incomingConnection(), and QLocalServer::incomingConnection().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ setSocketError()

void QAbstractSocket::setSocketError ( SocketError socketError)
protected

Sets the type of error that last occurred to socketError.

See also
setSocketState(), setErrorString()

Definition at line 2797 of file qabstractsocket.cpp.

Referenced by QLocalUnixSocket::setSocketError().

+ Here is the caller graph for this function:

◆ setSocketOption()

void QAbstractSocket::setSocketOption ( QAbstractSocket::SocketOption option,
const QVariant & value )
virtual
Since
4.6 Sets the given option to the value described by value.
Note
Since the options are set on an internal socket the options only apply if the socket has been created. This is only guaranteed to have happened after a call to bind(), or when connected() has been emitted.
See also
socketOption()

Reimplemented in QSslSocket.

Definition at line 1933 of file qabstractsocket.cpp.

References KeepAliveOption, QAbstractSocketEngine::KeepAliveOption, LowDelayOption, QAbstractSocketEngine::LowDelayOption, MulticastLoopbackOption, QAbstractSocketEngine::MulticastLoopbackOption, MulticastTtlOption, QAbstractSocketEngine::MulticastTtlOption, QAbstractSocketEngine::PathMtuInformation, PathMtuSocketOption, ReceiveBufferSizeSocketOption, QAbstractSocketEngine::ReceiveBufferSocketOption, SendBufferSizeSocketOption, QAbstractSocketEngine::SendBufferSocketOption, TypeOfServiceOption, and QAbstractSocketEngine::TypeOfServiceOption.

Referenced by QHttpNetworkConnectionChannel::_q_connected().

+ Here is the caller graph for this function:

◆ setSocketState()

void QAbstractSocket::setSocketState ( SocketState state)
protected

Sets the state of the socket to state.

See also
state()

Definition at line 2767 of file qabstractsocket.cpp.

References state().

Referenced by QSslSocket::setSocketDescriptor(), QLocalUnixSocket::setSocketState(), QSslSocket::waitForConnected(), and QSslSocket::waitForDisconnected().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ skipData()

qint64 QAbstractSocket::skipData ( qint64 maxSize)
overrideprotectedvirtual

\reimp

Reimplemented from QIODevice.

Reimplemented in QSslSocket.

Definition at line 1286 of file qabstractsocket.cpp.

References ConnectedState, d, and QIODevice::skipData().

+ Here is the call graph for this function:

◆ socketDescriptor()

qintptr QAbstractSocket::socketDescriptor ( ) const
virtual

Returns the native socket descriptor of the QAbstractSocket object if this is available; otherwise returns -1.

If the socket is using QNetworkProxy, the returned descriptor may not be usable with native socket functions.

The socket descriptor is not available when QAbstractSocket is in UnconnectedState.

See also
setSocketDescriptor()

Definition at line 1845 of file qabstractsocket.cpp.

References d.

Referenced by QSslSocketPrivate::_q_connectedSlot(), QSslSocketPrivate::bind(), setSocketDescriptor(), and QSslSocket::setSocketDescriptor().

+ Here is the caller graph for this function:

◆ socketOption()

◆ socketType()

QAbstractSocket::SocketType QAbstractSocket::socketType ( ) const

Returns the socket type (TCP, UDP, or other).

See also
QTcpSocket, QUdpSocket

Definition at line 2777 of file qabstractsocket.cpp.

Referenced by QAbstractSocket(), and QNativeSocketEnginePrivate::checkProxy().

+ Here is the caller graph for this function:

◆ state()

◆ stateChanged

void QAbstractSocket::stateChanged ( QAbstractSocket::SocketState socketState)
signal

This signal is emitted whenever QAbstractSocket's state changes.

The socketState parameter is the new state.

QAbstractSocket::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(), {Creating Custom Qt Types}

Referenced by QQmlDebugConnection::connectToHost(), connectToHost(), disconnectFromHost(), QSslSocket::disconnectFromHost(), setSocketDescriptor(), and waitForConnected().

+ Here is the caller graph for this function:

◆ waitForBytesWritten()

bool QAbstractSocket::waitForBytesWritten ( int msecs = 30000)
overridevirtual

\reimp

This function blocks until at least one byte has been written on the socket and the \l{QIODevice::}{bytesWritten()} signal has been emitted. The function will timeout after msecs milliseconds; the default timeout is 30000 milliseconds.

The function returns true if the bytesWritten() signal is emitted; otherwise it returns false (if an error occurred or the operation timed out).

Note
This function may fail randomly on Windows. Consider using the event loop and the bytesWritten() signal if your software will run on Windows.
See also
waitForReadyRead()

Reimplemented from QIODevice.

Reimplemented in QSslSocket.

Definition at line 2207 of file qabstractsocket.cpp.

References close(), ConnectedState, ConnectingState, d, deadline, HostLookupState, qDebug, qWarning, SocketTimeoutError, state(), UnconnectedState, and waitForConnected().

Referenced by QTcpServerConnection::disconnect().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ waitForConnected()

bool QAbstractSocket::waitForConnected ( int msecs = 30000)
virtual

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->connectToHost("imap", 143);
qDebug("Connected!");

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

Note
This function may wait slightly longer than msecs, depending on the time it takes to complete the host lookup.
Multiple calls to this functions do not accumulate the time. If the function times out, the connecting process will be aborted.
This function may fail randomly on Windows. Consider using the event loop and the connected() signal if your software will run on Windows.
See also
connectToHost(), connected()

Reimplemented in QSslSocket.

Definition at line 2048 of file qabstractsocket.cpp.

References QHostInfo::abortHostLookup(), ConnectedState, ConnectingState, d, deadline, DefaultConnectTimeout, disconnectFromHost(), emit, QHostInfo::fromName(), QDeadlineTimer::hasExpired(), HostLookupState, info, QDeadlineTimer::isForever(), qDebug, QTimer::remainingTime, QDeadlineTimer::remainingTimeAsDuration(), QHostAddress::setAddress(), QHostInfo::setAddresses(), SocketTimeoutError, state(), stateChanged(), timer, tr, and UnconnectedState.

Referenced by waitForBytesWritten(), QQmlDebugConnection::waitForConnected(), waitForDisconnected(), and waitForReadyRead().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ waitForDisconnected()

bool QAbstractSocket::waitForDisconnected ( int msecs = 30000)
virtual

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 QAbstractSocket 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:

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

Note
This function may fail randomly on Windows. Consider using the event loop and the disconnected() signal if your software will run on Windows.
See also
disconnectFromHost(), close()

Reimplemented in QSslSocket.

Definition at line 2291 of file qabstractsocket.cpp.

References close(), ConnectedState, ConnectingState, d, deadline, HostLookupState, qDebug, qWarning, SocketTimeoutError, state(), UnconnectedState, and waitForConnected().

+ Here is the call graph for this function:

◆ waitForReadyRead()

bool QAbstractSocket::waitForReadyRead ( int msecs = 30000)
overridevirtual

This function blocks until new data is available for reading and the \l{QIODevice::}{readyRead()} signal has been emitted.

The function will timeout after msecs milliseconds; the default timeout is 30000 milliseconds.

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

Note
This function may fail randomly on Windows. Consider using the event loop and the readyRead() signal if your software will run on Windows.
See also
waitForBytesWritten()

Reimplemented from QIODevice.

Reimplemented in QSslSocket.

Definition at line 2138 of file qabstractsocket.cpp.

References BoundState, close(), ConnectedState, ConnectingState, d, deadline, QDeadlineTimer::hasExpired(), HostLookupState, Q_ASSERT, qDebug, SocketTimeoutError, state(), UnconnectedState, and waitForConnected().

Referenced by test_tcpwait().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ writeData()

qint64 QAbstractSocket::writeData ( const char * data,
qint64 len )
overrideprotectedvirtual

\reimp

Implements QIODevice.

Reimplemented in QSslSocket, and QLocalUnixSocket.

Definition at line 2424 of file qabstractsocket.cpp.

References d, Q_INT64_C, qDebug, QIODevice::size(), TcpSocket, QtDebugUtils::toPrintable(), tr, UnconnectedState, and UnknownSocketError.

+ Here is the call graph for this function:

Member Data Documentation

◆ AnyIPProtocol

◆ IPv4Protocol

◆ IPv6Protocol

◆ UnknownNetworkLayerProtocol


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