![]() |
Qt 6.x
The Qt SDK
|
The QAbstractSocket class provides the base functionality common to all socket types. More...
#include <qabstractsocket.h>
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) |
![]() | |
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 () |
![]() | |
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) |
![]() | |
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. | |
virtual bool | isSequential () const |
Returns true if this device is sequential; 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 void | close () |
First emits aboutToClose(), then closes the device and sets its OpenMode to NotOpen. | |
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. | |
virtual qint64 | bytesAvailable () const |
Returns the number of bytes that are available for reading. | |
virtual qint64 | bytesToWrite () const |
For buffered devices, this function returns the number of bytes waiting to be written. | |
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) |
virtual bool | waitForReadyRead (int msecs) |
Blocks until new data is available for reading and the readyRead() signal has been emitted, or until msecs milliseconds have passed. | |
virtual bool | waitForBytesWritten (int msecs) |
For buffered devices, this function waits until a payload of buffered written data has been written to the device and the bytesWritten() signal has been emitted, or until msecs milliseconds have passed. | |
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. | |
![]() | |
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< QString > | bindableObjectName () |
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). | |
QThread * | thread () const |
Returns the thread in which the object lives. | |
void | moveToThread (QThread *thread) |
Changes the thread affinity for this object and its children. | |
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::milliseconds time, Qt::TimerType timerType=Qt::CoarseTimer) |
void | killTimer (int id) |
Kills the timer with timer identifier, id. | |
template<typename T > | |
T | findChild (const QString &aName=QString(), 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 (const QString &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 > | |
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 QObjectList & | children () 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< QByteArray > | dynamicPropertyNames () const |
QBindingStorage * | bindingStorage () |
const QBindingStorage * | bindingStorage () const |
QObject * | parent () 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) | |
![]() | |
QIODevice (QIODevicePrivate &dd, QObject *parent=nullptr) | |
virtual qint64 | readData (char *data, qint64 maxlen)=0 |
Reads up to maxSize bytes from the device into data, and returns the number of bytes read or -1 if an error occurred. | |
virtual qint64 | readLineData (char *data, qint64 maxlen) |
Reads up to maxSize characters into data and returns the number of characters read. | |
virtual qint64 | skipData (qint64 maxSize) |
virtual qint64 | writeData (const char *data, qint64 len)=0 |
Writes up to maxSize bytes from data to the device. | |
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. | |
![]() | |
QObject * | sender () 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) | |
![]() | |
~QIODeviceBase ()=default | |
Additional Inherited Members | |
![]() | |
void | deleteLater () |
\threadsafe | |
![]() | |
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) |
![]() | |
QScopedPointer< QObjectData > | d_ptr |
![]() | |
QString | objectName |
the name of this object | |
![]() | |
template< class T > T | qobject_cast (const QObject *object) |
Returns the given object cast to type T if the object is of type T (or of a subclass); otherwise returns \nullptr. | |
template< typename T > T | qFindChildqFindChildren (const QObject *obj, const QString &name)() |
template< typename T > QList< T > | qFindChildrenqFindChildren (const QObject *obj, const QString &name)() |
QObjectList | |
\macro Q_CLASSINFO(Name, Value) | |
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:
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.
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>>().
Definition at line 30 of file qabstractsocket.h.
Definition at line 54 of file qabstractsocket.h.
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
Enumerator | |
---|---|
DefaultForPlatform | |
ShareAddress | |
DontShareAddress | |
ReuseAddressHint |
Definition at line 110 of file qabstractsocket.h.
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.
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.
Definition at line 61 of file qabstractsocket.h.
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
Enumerator | |
---|---|
LowDelayOption | |
KeepAliveOption | |
MulticastTtlOption | |
MulticastLoopbackOption | |
TypeOfServiceOption | |
SendBufferSizeSocketOption | |
ReceiveBufferSizeSocketOption | |
PathMtuSocketOption |
Definition at line 99 of file qabstractsocket.h.
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.
Enumerator | |
---|---|
UnconnectedState | |
HostLookupState | |
ConnectingState | |
ConnectedState | |
BoundState | |
ListeningState | |
ClosingState |
Definition at line 89 of file qabstractsocket.h.
This enum describes the transport layer protocol.
\value TcpSocket TCP \value UdpSocket UDP \value SctpSocket SCTP \value UnknownSocketType Other than TCP, UDP and SCTP
Enumerator | |
---|---|
TcpSocket | |
UdpSocket | |
SctpSocket | |
UnknownSocketType |
Definition at line 36 of file qabstractsocket.h.
QAbstractSocket::QAbstractSocket | ( | SocketType | socketType, |
QObject * | parent | ||
) |
Creates a new abstract socket of type socketType.
The parent argument is passed to QObject's constructor.
Definition at line 1399 of file qabstractsocket.cpp.
|
virtual |
Destroys the socket.
Definition at line 1407 of file qabstractsocket.cpp.
References abort(), d, qDebug, and UnconnectedState.
|
protected |
Constructs a new abstract socket of type socketType. The parent argument is passed to QObject's constructor.
Definition at line 1380 of file qabstractsocket.cpp.
References d, QObject::parent(), qDebug, SctpSocket, socketType(), TcpSocket, and UdpSocket.
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.
Definition at line 2341 of file qabstractsocket.cpp.
References close(), d, and qDebug.
Referenced by ~QAbstractSocket(), and QHttpNetworkConnectionChannel::abort().
|
virtual |
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 1486 of file qabstractsocket.cpp.
References d.
Referenced by QSslSocketPrivate::bind(), DtlsServer::listen(), QUdpSocket::writeDatagram(), and QUdpSocket::writeDatagram().
|
inline |
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().
|
inline |
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().
|
overridevirtual |
Returns the number of incoming bytes that are waiting to be read.
Reimplemented from QIODevice.
Reimplemented in QSslSocket.
Definition at line 1746 of file qabstractsocket.cpp.
References QIODevice::bytesAvailable(), d, and qDebug.
Referenced by QHttpNetworkConnectionChannel::_q_disconnected(), QHttpNetworkConnectionChannel::_q_error(), QSslSocketPrivate::_q_errorSlot(), QHttpProtocolHandler::_q_readyRead(), QSslSocketPrivate::_q_readyReadSlot(), QHttpProtocolHandler::_q_receiveReply(), QHttpNetworkConnectionChannel::allDone(), QSslSocket::bytesAvailable(), QSslServerPrivate::checkClientHelloAndContinue(), QSocks5PasswordAuthenticator::continueAuthenticate(), QTlsPrivate::TlsCryptographSchannel::continueHandshake(), QTlsPrivate::TlsCryptographSchannel::disconnected(), QTlsPrivate::TlsCryptographSecureTransport::disconnected(), QHttpNetworkReplyPrivate::getChunkSize(), QHttpNetworkReplyPrivate::readBody(), QHttpNetworkReplyPrivate::readBodyFast(), QHttpNetworkReplyPrivate::readReplyBodyChunked(), QHttpNetworkReplyPrivate::readReplyBodyRaw(), QHttpProtocolHandler::sendRequest(), and QTlsPrivate::TlsCryptographSchannel::transmit().
|
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.
Reimplemented from QIODevice.
Reimplemented in QSslSocket.
Definition at line 1732 of file qabstractsocket.cpp.
References QIODevice::bytesToWrite(), and qDebug.
Referenced by QTcpServerConnection::disconnect(), and QHttpProtocolHandler::sendRequest().
|
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.
Reimplemented from QIODevice.
Reimplemented in QSctpSocket, and QSslSocket.
Definition at line 2589 of file qabstractsocket.cpp.
References QIODevice::close(), d, disconnectFromHost(), qDebug, and UnconnectedState.
Referenced by QHttpNetworkConnectionPrivate::~QHttpNetworkConnectionPrivate(), abort(), QHttpNetworkConnectionChannel::close(), QSocks5PasswordAuthenticator::continueAuthenticate(), waitForBytesWritten(), waitForDisconnected(), and waitForReadyRead().
|
signal |
This signal is emitted after connectToHost() has been called and a connection has been successfully established.
Referenced by QQmlDebugConnection::connectToHost().
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 1715 of file qabstractsocket.cpp.
References connectToHost(), QIODevice::openMode(), and qDebug.
|
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.
Reimplemented in QSslSocket, and QSslSocket.
Definition at line 1614 of file qabstractsocket.cpp.
References QHostInfo::abortHostLookup(), BoundState, 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(), SLOT, stateChanged(), QString::toLatin1(), tr, QIODeviceBase::Unbuffered, UnconnectedState, UnknownSocketError, and UnsupportedSocketOperationError.
Referenced by connectToHost(), QQmlDebugConnection::connectToHost(), QHttpNetworkConnectionChannel::ensureConnection(), and test_tcpwait().
|
signal |
This signal is emitted when the socket has been disconnected.
Referenced by QQmlDebugConnection::connectToHost(), and 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.
Reimplemented in QSctpSocket, and QSslSocket.
Definition at line 2608 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().
QAbstractSocket::SocketError QAbstractSocket::error | ( | ) | const |
Returns the type of error that last occurred.
Definition at line 2783 of file qabstractsocket.cpp.
Referenced by QSslSocketPrivate::_q_errorSlot(), QHttpProtocolHandler::_q_readyRead(), QLocalUnixSocket::setSocketError(), QTlsPrivate::TlsCryptographSchannel::transmit(), and QDtlsPrivateOpenSSL::writeDatagramEncrypted().
|
signal |
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 a QTimer::singleShot() with 0 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().
Referenced by QQmlDebugConnection::connectToHost(), and QSslServer::incomingConnection().
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.
Definition at line 2373 of file qabstractsocket.cpp.
Referenced by QSslSocket::close(), QQmlDebugConnectionPrivate::flush(), QSslSocketPrivate::flush(), QTcpServerConnection::flush(), and QRfbRawEncoder::write().
|
signal |
This signal is emitted after connectToHost() has been called and the host lookup has succeeded.
|
overridevirtual |
bool QAbstractSocket::isValid | ( | ) | const |
Returns true
if the socket is valid and ready for use; otherwise returns false
.
Definition at line 1586 of file qabstractsocket.cpp.
References QIODevice::isOpen().
Referenced by ServerAcceptanceThread::javaNewSocket(), QBluetoothServer::nextPendingConnection(), and QUdpSocket::setMulticastInterface().
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.
Definition at line 1782 of file qabstractsocket.cpp.
References d.
Referenced by QHttpNetworkConnectionChannel::_q_connected(), QSslSocketPrivate::_q_connectedSlot(), and QSslSocketPrivate::bind().
quint16 QAbstractSocket::localPort | ( | ) | const |
Returns the host port number (in native byte order) of the local socket if available; otherwise returns 0.
Definition at line 1766 of file qabstractsocket.cpp.
References d.
Referenced by QSslSocketPrivate::_q_connectedSlot(), and QSslSocketPrivate::bind().
QAbstractSocket::PauseModes QAbstractSocket::pauseMode | ( | ) | const |
Returns the pause mode of this socket.
Definition at line 1441 of file qabstractsocket.cpp.
Referenced by setPauseMode().
QHostAddress QAbstractSocket::peerAddress | ( | ) | const |
Returns the address of the connected peer if the socket is in ConnectedState; otherwise returns QHostAddress::Null.
Definition at line 1806 of file qabstractsocket.cpp.
References d.
Referenced by QHttpNetworkConnectionChannel::_q_connected(), and QSslSocketPrivate::_q_connectedSlot().
QString QAbstractSocket::peerName | ( | ) | const |
Returns the name of the peer as specified by connectToHost(), or an empty QString if connectToHost() has not been called.
Definition at line 1818 of file qabstractsocket.cpp.
References d.
Referenced by QSslSocketPrivate::_q_connectedSlot(), and QHttpNetworkConnectionPrivate::errorDetail().
quint16 QAbstractSocket::peerPort | ( | ) | const |
Returns the port of the connected peer if the socket is in ConnectedState; otherwise returns 0.
Definition at line 1794 of file qabstractsocket.cpp.
References d.
Referenced by QSslSocketPrivate::_q_connectedSlot().
QString QAbstractSocket::protocolTag | ( | ) | const |
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.
Definition at line 2850 of file qabstractsocket.cpp.
References d.
QNetworkProxy QAbstractSocket::proxy | ( | ) | const |
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.
Definition at line 2833 of file qabstractsocket.cpp.
References d.
Referenced by QNativeSocketEnginePrivate::checkProxy(), QSslSocket::connectToHost(), and QHttpNetworkConnectionChannel::ensureConnection().
|
signal |
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.
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.
Definition at line 2705 of file qabstractsocket.cpp.
\reimp
Implements QIODevice.
Reimplemented in QSctpSocket, QSslSocket, and QLocalUnixSocket.
Definition at line 2380 of file qabstractsocket.cpp.
References ConnectedState, d, qDebug, QtDebugUtils::toPrintable(), and UnconnectedState.
\reimp
Reimplemented from QIODevice.
Reimplemented in QSctpSocket.
Definition at line 2413 of file qabstractsocket.cpp.
References QIODevice::readLineData().
|
virtual |
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.
Reimplemented in QSslSocket.
Definition at line 1429 of file qabstractsocket.cpp.
References QAbstractSocketPrivate::resumeSocketNotifiers().
Referenced by QSslSocketPrivate::_q_resumeImplementation().
|
protected |
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()).
Definition at line 2518 of file qabstractsocket.cpp.
References d.
Referenced by QSslSocket::setSocketDescriptor().
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()).
Definition at line 2496 of file qabstractsocket.cpp.
References d.
Referenced by QSslSocket::setSocketDescriptor().
void QAbstractSocket::setPauseMode | ( | PauseModes | pauseMode | ) |
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.
Definition at line 1461 of file qabstractsocket.cpp.
References pauseMode().
|
protected |
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.
Definition at line 2556 of file qabstractsocket.cpp.
References d.
Referenced by QSslSocket::setSocketDescriptor().
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.
Definition at line 2574 of file qabstractsocket.cpp.
References d.
Referenced by QSslSocket::setSocketDescriptor().
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.
Definition at line 2537 of file qabstractsocket.cpp.
References d.
Referenced by QSslSocket::setSocketDescriptor().
Sets the protocol tag for this socket to tag.
Definition at line 2864 of file qabstractsocket.cpp.
void QAbstractSocket::setProxy | ( | const QNetworkProxy & | networkProxy | ) |
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.
Definition at line 2818 of file qabstractsocket.cpp.
References d.
Referenced by QHttpNetworkConnectionChannel::ensureConnection(), QHttpNetworkConnectionChannel::init(), QSocks5SocketEnginePrivate::initialize(), and QHttpNetworkConnectionChannel::setProxy().
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.
Reimplemented in QSslSocket.
Definition at line 2732 of file qabstractsocket.cpp.
References ConnectedState, d, and QIODevice::size().
Referenced by QHttpNetworkConnectionChannel::ensureConnection().
|
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.
Reimplemented in QSslSocket.
Definition at line 1855 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().
|
protected |
Sets the type of error that last occurred to socketError.
Definition at line 2793 of file qabstractsocket.cpp.
Referenced by QLocalUnixSocket::setSocketError().
|
virtual |
Reimplemented in QSslSocket.
Definition at line 1924 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().
|
protected |
Sets the state of the socket to state.
Definition at line 2763 of file qabstractsocket.cpp.
References state().
Referenced by QSslSocket::setSocketDescriptor(), QLocalUnixSocket::setSocketState(), QSslSocket::waitForConnected(), and QSslSocket::waitForDisconnected().
\reimp
Reimplemented from QIODevice.
Reimplemented in QSslSocket.
Definition at line 1277 of file qabstractsocket.cpp.
References ConnectedState, d, and QIODevice::skipData().
|
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.
Definition at line 1836 of file qabstractsocket.cpp.
References d.
Referenced by QSslSocketPrivate::_q_connectedSlot(), QLocalServerPrivate::_q_onNewConnection(), QSslSocketPrivate::bind(), QLocalSocket::setSocketDescriptor(), setSocketDescriptor(), and QSslSocket::setSocketDescriptor().
|
virtual |
Reimplemented in QSslSocket.
Definition at line 1970 of file qabstractsocket.cpp.
References KeepAliveOption, QAbstractSocketEngine::KeepAliveOption, LowDelayOption, QAbstractSocketEngine::LowDelayOption, MulticastLoopbackOption, QAbstractSocketEngine::MulticastLoopbackOption, MulticastTtlOption, QAbstractSocketEngine::MulticastTtlOption, QAbstractSocketEngine::PathMtuInformation, PathMtuSocketOption, ReceiveBufferSizeSocketOption, QAbstractSocketEngine::ReceiveBufferSocketOption, ret, SendBufferSizeSocketOption, QAbstractSocketEngine::SendBufferSocketOption, TypeOfServiceOption, and QAbstractSocketEngine::TypeOfServiceOption.
QAbstractSocket::SocketType QAbstractSocket::socketType | ( | ) | const |
Returns the socket type (TCP, UDP, or other).
Definition at line 2773 of file qabstractsocket.cpp.
Referenced by QAbstractSocket(), and QNativeSocketEnginePrivate::checkProxy().
QAbstractSocket::SocketState QAbstractSocket::state | ( | ) | const |
Returns the state of the socket.
Definition at line 2753 of file qabstractsocket.cpp.
Referenced by QHttpNetworkConnectionChannel::_q_error(), QHttpProtocolHandler::_q_readyRead(), QHttpProtocolHandler::_q_receiveReply(), QHttpNetworkConnectionPrivate::_q_startNextRequest(), QHttpNetworkConnectionChannel::abort(), QHttpNetworkConnectionChannel::allDone(), QHttpNetworkConnectionChannel::close(), QHttpNetworkConnectionChannel::detectPipeliningSupport(), QTlsPrivate::TlsCryptographSchannel::disconnectFromHost(), QHttpNetworkConnectionChannel::ensureConnection(), QHttpNetworkConnectionPrivate::fillPipeline(), QTcpServerConnection::isConnected(), DtlsServer::listen(), dtlsbio::q_dgram_write(), QSslSocket::setSocketDescriptor(), QLocalUnixSocket::setSocketState(), setSocketState(), QSslSocket::startClientEncryption(), QTlsPrivate::TlsCryptographSchannel::transmit(), waitForBytesWritten(), waitForConnected(), waitForDisconnected(), QSslSocket::waitForDisconnected(), waitForReadyRead(), QRfbRawEncoder::write(), QUdpSocket::writeDatagram(), and QUdpSocket::writeDatagram().
|
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().
Referenced by QQmlDebugConnection::connectToHost(), connectToHost(), disconnectFromHost(), QSslSocket::disconnectFromHost(), setSocketDescriptor(), and waitForConnected().
|
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).
Reimplemented from QIODevice.
Reimplemented in QSslSocket.
Definition at line 2201 of file qabstractsocket.cpp.
References close(), ConnectedState, ConnectingState, d, QElapsedTimer::elapsed(), forever, HostLookupState, qDebug, qt_subtract_from_timeout(), qWarning, SocketTimeoutError, QElapsedTimer::start(), state(), UnconnectedState, and waitForConnected().
Referenced by QTcpServerConnection::disconnect().
|
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:
If msecs is -1, this function will not time out.
Reimplemented in QSslSocket.
Definition at line 2039 of file qabstractsocket.cpp.
References QHostInfo::abortHostLookup(), ConnectedState, ConnectingState, d, DefaultConnectTimeout, disconnectFromHost(), QElapsedTimer::elapsed(), emit, QHostInfo::fromName(), HostLookupState, info, qDebug, qt_subtract_from_timeout(), QHostAddress::setAddress(), SocketTimeoutError, QElapsedTimer::start(), state(), stateChanged(), tr, and UnconnectedState.
Referenced by waitForBytesWritten(), QQmlDebugConnection::waitForConnected(), waitForDisconnected(), and waitForReadyRead().
|
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.
Reimplemented in QSslSocket.
Definition at line 2286 of file qabstractsocket.cpp.
References close(), ConnectedState, ConnectingState, d, QElapsedTimer::elapsed(), forever, HostLookupState, qDebug, qt_subtract_from_timeout(), qWarning, SocketTimeoutError, QElapsedTimer::start(), state(), UnconnectedState, and waitForConnected().
|
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).
Reimplemented from QIODevice.
Reimplemented in QSslSocket.
Definition at line 2131 of file qabstractsocket.cpp.
References BoundState, close(), ConnectedState, ConnectingState, d, QElapsedTimer::elapsed(), HostLookupState, Q_ASSERT, qDebug, qt_subtract_from_timeout(), SocketTimeoutError, QElapsedTimer::start(), state(), UnconnectedState, and waitForConnected().
Referenced by test_tcpwait().
\reimp
Implements QIODevice.
Reimplemented in QSslSocket, and QLocalUnixSocket.
Definition at line 2420 of file qabstractsocket.cpp.
References d, Q_INT64_C, qDebug, QIODevice::size(), TcpSocket, QtDebugUtils::toPrintable(), tr, UnconnectedState, and UnknownSocketError.
|
staticconstexpr |
Definition at line 57 of file qabstractsocket.h.
Referenced by QHttpNetworkConnectionChannel::_q_connected(), QAbstractSocketPrivate::_q_startConnecting(), QNativeSocketEnginePrivate::adjustAddressProtocol(), QSocks5SocketEngine::bind(), convertToLevelAndOption(), convertToLevelAndOption(), QNativeSocketEnginePrivate::createNewSocket(), QNativeSocketEnginePrivate::fetchConnectionParameters(), QNativeSocketEngine::joinMulticastGroup(), QTcpServer::listen(), QNativeSocketEnginePrivate::nativeBind(), QNativeSocketEnginePrivate::nativeMulticastInterface(), QNativeSocketEnginePrivate::nativeSetMulticastInterface(), QHttpNetworkConnectionPrivate::startNetworkLayerStateLookup(), and QTest::toString< QHostAddress >().
|
staticconstexpr |
Definition at line 55 of file qabstractsocket.h.
Referenced by QHttpNetworkConnectionChannel::_q_connected(), QHttpNetworkConnectionPrivate::_q_hostLookupFinished(), QHttpNetworkConnectionPrivate::_q_startNextRequest(), QNativeSocketEnginePrivate::adjustAddressProtocol(), convertToLevelAndOption(), convertToLevelAndOption(), dtlsutil::cookie_for_peer(), QNativeSocketEnginePrivate::createNewSocket(), QNativeSocketEnginePrivate::fetchConnectionParameters(), QNativeSocketEngine::initialize(), QAbstractSocketPrivate::initSocketLayer(), QNativeSocketEngine::joinMulticastGroup(), QTcpServer::listen(), multicastMembershipHelper(), multicastMembershipHelper(), QNativeSocketEnginePrivate::nativeSetMulticastInterface(), QNetworkCookie::normalize(), postProcess(), dtlsbio::q_dgram_ctrl(), qt_socks5_set_host_address_and_port(), QHostInfoAgent::reverseLookup(), QNetmask::setPrefixLength(), QHttpNetworkConnectionPrivate::shouldEmitChannelError(), QHttpNetworkConnectionPrivate::startHostInfoLookup(), QHttpNetworkConnectionPrivate::startNetworkLayerStateLookup(), and QTest::toString< QHostAddress >().
|
staticconstexpr |
Definition at line 56 of file qabstractsocket.h.
Referenced by QHttpNetworkConnectionChannel::_q_connected(), QHttpNetworkConnectionPrivate::_q_hostLookupFinished(), QHttpNetworkConnectionPrivate::_q_startNextRequest(), QNativeSocketEnginePrivate::adjustAddressProtocol(), applyNameServer(), convertToLevelAndOption(), convertToLevelAndOption(), dtlsutil::cookie_for_peer(), QNativeSocketEnginePrivate::createNewSocket(), QNativeSocketEnginePrivate::fetchConnectionParameters(), QNativeSocketEngine::initialize(), QAbstractSocketPrivate::initSocketLayer(), QNativeSocketEngine::joinMulticastGroup(), multicastMembershipHelper(), multicastMembershipHelper(), QNativeSocketEnginePrivate::nativeBind(), QNativeSocketEnginePrivate::nativeMulticastInterface(), QNativeSocketEnginePrivate::nativeSetMulticastInterface(), QNetworkCookie::normalize(), QNativeSocketEnginePrivate::option(), QHttpNetworkConnectionPrivate::prepareRequest(), dtlsbio::q_dgram_ctrl(), qt_socks5_set_host_address_and_port(), QNetmask::setPrefixLength(), QNetworkConnectionMonitorPrivate::setTargets(), QHttpNetworkConnectionPrivate::shouldEmitChannelError(), QHttpNetworkConnectionPrivate::startHostInfoLookup(), QHttpNetworkConnectionPrivate::startNetworkLayerStateLookup(), QNetworkCookie::toRawForm(), and QTest::toString< QHostAddress >().
|
staticconstexpr |
Definition at line 58 of file qabstractsocket.h.
Referenced by QAbstractSocketPrivate::_q_startConnecting(), QNativeSocketEnginePrivate::adjustAddressProtocol(), QAbstractSocketPrivate::bind(), QNetworkDatagram::destinationPort(), QNativeSocketEnginePrivate::fetchConnectionParameters(), QNetworkDatagram::isValid(), QNetworkDatagram::senderPort(), QAbstractSocketPrivate::startConnectingByName(), and QTest::toString< QHostAddress >().