Qt 4.8
Public Types | Signals | Public Functions | Protected Slots | Protected Functions | List of all members
QAbstractSocket Class Reference

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

#include <qabstractsocket.h>

Inheritance diagram for QAbstractSocket:
QIODevice QObject QTcpSocket QUdpSocket QDeclarativeDebugConnection QSslSocket

Public Types

enum  NetworkLayerProtocol { IPv4Protocol, IPv6Protocol, UnknownNetworkLayerProtocol = -1 }
 This enum describes the network layer protocol values used in Qt. More...
 
enum  SocketError {
  ConnectionRefusedError, RemoteHostClosedError, HostNotFoundError, SocketAccessError,
  SocketResourceError, SocketTimeoutError, DatagramTooLargeError, NetworkError,
  AddressInUseError, SocketAddressNotAvailableError, UnsupportedSocketOperationError, UnfinishedSocketOperationError,
  ProxyAuthenticationRequiredError, SslHandshakeFailedError, ProxyConnectionRefusedError, ProxyConnectionClosedError,
  ProxyConnectionTimeoutError, ProxyNotFoundError, ProxyProtocolError, UnknownSocketError = -1
}
 This enum describes the socket errors that can occur. More...
 
enum  SocketOption { LowDelayOption, KeepAliveOption, MulticastTtlOption, MulticastLoopbackOption }
 This enum represents the options that can be set on a socket. More...
 
enum  SocketState {
  UnconnectedState, HostLookupState, ConnectingState, ConnectedState,
  BoundState, ListeningState, ClosingState
}
 This enum describes the different states in which a socket can be. More...
 
enum  SocketType { TcpSocket, UdpSocket, UnknownSocketType = -1 }
 This enum describes the transport layer protocol. More...
 
- Public Types inherited from QIODevice
enum  OpenModeFlag {
  NotOpen = 0x0000, ReadOnly = 0x0001, WriteOnly = 0x0002, ReadWrite = ReadOnly | WriteOnly,
  Append = 0x0004, Truncate = 0x0008, Text = 0x0010, Unbuffered = 0x0020
}
 This enum is used with open() to describe the mode in which a device is opened. More...
 

Signals

void connected ()
 This signal is emitted after connectToHost() has been called and a connection has been successfully established. More...
 
void disconnected ()
 This signal is emitted when the socket has been disconnected. More...
 
void error (QAbstractSocket::SocketError)
 This signal is emitted after an error occurred. More...
 
void hostFound ()
 This signal is emitted after connectToHost() has been called and the host lookup has succeeded. More...
 
void proxyAuthenticationRequired (const QNetworkProxy &proxy, QAuthenticator *authenticator)
 
void stateChanged (QAbstractSocket::SocketState)
 This signal is emitted whenever QAbstractSocket's state changes. More...
 
- Signals inherited from QIODevice
void aboutToClose ()
 This signal is emitted when the device is about to close. More...
 
void bytesWritten (qint64 bytes)
 This signal is emitted every time a payload of data has been written to the device. More...
 
void readChannelFinished ()
 This signal is emitted when the input (reading) stream is closed in this device. More...
 
void readyRead ()
 This signal is emitted once every time new data is available for reading from the device. More...
 
- Signals inherited from QObject
void destroyed (QObject *=0)
 This signal is emitted immediately before the object obj is destroyed, and can not be blocked. More...
 

Public Functions

void abort ()
 Aborts the current connection and resets the socket. More...
 
bool atEnd () const
 Returns true if no more data is currently available for reading; otherwise returns false. More...
 
qint64 bytesAvailable () const
 Returns the number of incoming bytes that are waiting to be read. More...
 
qint64 bytesToWrite () const
 Returns the number of bytes that are waiting to be written. More...
 
bool canReadLine () const
 Returns true if a line of data can be read from the socket; otherwise returns false. More...
 
void close ()
 Closes the I/O device for the socket, disconnects the socket's connection with the host, closes the socket, and resets the name, address, port number and underlying socket descriptor. More...
 
void connectToHost (const QString &hostName, quint16 port, OpenMode mode=ReadWrite)
 Attempts to make a connection to hostName on the given port. More...
 
void connectToHost (const QHostAddress &address, quint16 port, OpenMode mode=ReadWrite)
 Attempts to make a connection to address on port port. More...
 
void disconnectFromHost ()
 Attempts to close the socket. More...
 
SocketError error () const
 Returns the type of error that last occurred. More...
 
bool flush ()
 This function writes as much as possible from the internal write buffer to the underlying network socket, without blocking. More...
 
bool isSequential () const
 Reimplemented Function More...
 
bool isValid () const
 Returns true if the socket is valid and ready for use; otherwise returns false. More...
 
QHostAddress localAddress () const
 Returns the host address of the local socket if available; otherwise returns QHostAddress::Null. More...
 
quint16 localPort () const
 Returns the host port number (in native byte order) of the local socket if available; otherwise returns 0. More...
 
QHostAddress peerAddress () const
 Returns the address of the connected peer if the socket is in ConnectedState; otherwise returns QHostAddress::Null. More...
 
QString peerName () const
 Returns the name of the peer as specified by connectToHost(), or an empty QString if connectToHost() has not been called. More...
 
quint16 peerPort () const
 Returns the port of the connected peer if the socket is in ConnectedState; otherwise returns 0. More...
 
QNetworkProxy proxy () const
 Returns the network proxy for this socket. More...
 
 QAbstractSocket (SocketType socketType, QObject *parent)
 Creates a new abstract socket of type socketType. More...
 
qint64 readBufferSize () const
 Returns the size of the internal read buffer. More...
 
void setProxy (const QNetworkProxy &networkProxy)
 Sets the explicit network proxy for this socket to networkProxy. More...
 
void setReadBufferSize (qint64 size)
 Sets the size of QAbstractSocket's internal read buffer to be size bytes. More...
 
bool setSocketDescriptor (int socketDescriptor, SocketState state=ConnectedState, OpenMode openMode=ReadWrite)
 Initializes QAbstractSocket with the native socket descriptor socketDescriptor. More...
 
void setSocketOption (QAbstractSocket::SocketOption option, const QVariant &value)
 Sets the given option to the value described by value. More...
 
int socketDescriptor () const
 Returns the native socket descriptor of the QAbstractSocket object if this is available; otherwise returns -1. More...
 
QVariant socketOption (QAbstractSocket::SocketOption option)
 Returns the value of the option option. More...
 
SocketType socketType () const
 Returns the socket type (TCP, UDP, or other). More...
 
SocketState state () const
 Returns the state of the socket. More...
 
bool waitForBytesWritten (int msecs=30000)
 Reimplemented Function More...
 
bool waitForConnected (int msecs=30000)
 Waits until the socket is connected, up to msecs milliseconds. More...
 
bool waitForDisconnected (int msecs=30000)
 Waits until the socket has disconnected, up to msecs milliseconds. More...
 
bool waitForReadyRead (int msecs=30000)
 This function blocks until new data is available for reading and the QIODevice::readyRead() signal has been emitted. More...
 
virtual ~QAbstractSocket ()
 Destroys the socket. More...
 
- Public Functions inherited from QIODevice
QString errorString () const
 Returns a human-readable description of the last device error that occurred. More...
 
bool getChar (char *c)
 Reads one character from the device and stores it in c. More...
 
bool isOpen () const
 Returns true if the device is open; otherwise returns false. More...
 
bool isReadable () const
 Returns true if data can be read from the device; otherwise returns false. More...
 
bool isTextModeEnabled () const
 Returns true if the Text flag is enabled; otherwise returns false. More...
 
bool isWritable () const
 Returns true if data can be written to the device; otherwise returns false. More...
 
virtual bool open (OpenMode mode)
 Opens the device and sets its OpenMode to mode. More...
 
OpenMode openMode () const
 Returns the mode in which the device has been opened; i.e. More...
 
qint64 peek (char *data, qint64 maxlen)
 Reads at most maxSize bytes from the device into data, without side effects (i. More...
 
QByteArray peek (qint64 maxlen)
 Peeks at most maxSize bytes from the device, returning the data peeked as a QByteArray. More...
 
virtual qint64 pos () const
 For random-access devices, this function returns the position that data is written to or read from. More...
 
bool putChar (char c)
 Writes the character c to the device. More...
 
 QIODevice ()
 Constructs a QIODevice object. More...
 
 QIODevice (QObject *parent)
 Constructs a QIODevice object with the given parent. More...
 
qint64 read (char *data, qint64 maxlen)
 Reads at most maxSize bytes from the device into data, and returns the number of bytes read. More...
 
QByteArray read (qint64 maxlen)
 Reads at most maxSize bytes from the device, and returns the data read as a QByteArray. More...
 
QByteArray readAll ()
 Reads all available data from the device, and returns it as a QByteArray. More...
 
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. More...
 
QByteArray readLine (qint64 maxlen=0)
 Reads a line from the device, but no more than maxSize characters, and returns the result as a QByteArray. More...
 
virtual bool reset ()
 Seeks to the start of input for random-access devices. More...
 
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. More...
 
void setTextModeEnabled (bool enabled)
 If enabled is true, this function sets the Text flag on the device; otherwise the Text flag is removed. More...
 
virtual qint64 size () const
 For open random-access devices, this function returns the size of the device. More...
 
void ungetChar (char c)
 Puts the character c back into the device, and decrements the current position unless the position is 0. More...
 
qint64 write (const char *data, qint64 len)
 Writes at most maxSize bytes of data from data to the device. More...
 
qint64 write (const char *data)
 Writes data from a zero-terminated string of 8-bit characters to the device. More...
 
qint64 write (const QByteArray &data)
 Writes the content of byteArray to the device. More...
 
virtual ~QIODevice ()
 The destructor is virtual, and QIODevice is an abstract base class. More...
 
- Public Functions inherited from QObject
bool blockSignals (bool b)
 If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). More...
 
const QObjectListchildren () const
 Returns a list of child objects. More...
 
bool connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const
 
bool disconnect (const char *signal=0, const QObject *receiver=0, const char *member=0)
 
bool disconnect (const QObject *receiver, const char *member=0)
 
void dumpObjectInfo ()
 Dumps information about signal connections, etc. More...
 
void dumpObjectTree ()
 Dumps a tree of children to the debug output. More...
 
QList< QByteArraydynamicPropertyNames () const
 Returns the names of all properties that were dynamically added to the object using setProperty(). More...
 
virtual bool event (QEvent *)
 This virtual function receives events to an object and should return true if the event e was recognized and processed. More...
 
virtual bool eventFilter (QObject *, QEvent *)
 Filters events if this object has been installed as an event filter for the watched object. More...
 
template<typename T >
findChild (const QString &aName=QString()) const
 Returns the child of this object that can be cast into type T and that is called name, or 0 if there is no such object. More...
 
template<typename T >
QList< T > findChildren (const QString &aName=QString()) 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. More...
 
template<typename T >
QList< T > findChildren (const QRegExp &re) const
 
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. More...
 
void installEventFilter (QObject *)
 Installs an event filter filterObj on this object. More...
 
bool isWidgetType () const
 Returns true if the object is a widget; otherwise returns false. More...
 
void killTimer (int id)
 Kills the timer with timer identifier, id. More...
 
virtual const QMetaObjectmetaObject () const
 Returns a pointer to the meta-object of this object. More...
 
void moveToThread (QThread *thread)
 Changes the thread affinity for this object and its children. More...
 
QString objectName () const
 
QObjectparent () const
 Returns a pointer to the parent object. More...
 
QVariant property (const char *name) const
 Returns the value of the object's name property. More...
 
Q_INVOKABLE QObject (QObject *parent=0)
 Constructs an object with parent object parent. More...
 
void removeEventFilter (QObject *)
 Removes an event filter object obj from this object. More...
 
void setObjectName (const QString &name)
 
void setParent (QObject *)
 Makes the object a child of parent. More...
 
bool setProperty (const char *name, const QVariant &value)
 Sets the value of the object's name property to value. More...
 
void setUserData (uint id, QObjectUserData *data)
 
bool signalsBlocked () const
 Returns true if signals are blocked; otherwise returns false. More...
 
int startTimer (int interval)
 Starts a timer and returns a timer identifier, or returns zero if it could not start a timer. More...
 
QThreadthread () const
 Returns the thread in which the object lives. More...
 
QObjectUserDatauserData (uint id) const
 
virtual ~QObject ()
 Destroys the object, deleting all its child objects. More...
 

Protected Slots

void connectToHostImplementation (const QString &hostName, quint16 port, OpenMode mode=ReadWrite)
 Contains the implementation of connectToHost(). More...
 
void disconnectFromHostImplementation ()
 Contains the implementation of disconnectFromHost(). More...
 

Protected Functions

 QAbstractSocket (SocketType socketType, QAbstractSocketPrivate &dd, QObject *parent=0)
 Constructs a new abstract socket of type socketType. More...
 
qint64 readData (char *data, qint64 maxlen)
 Reimplemented Function More...
 
qint64 readLineData (char *data, qint64 maxlen)
 Reimplemented Function More...
 
void setLocalAddress (const QHostAddress &address)
 Sets the address on the local side of a connection to address. More...
 
void setLocalPort (quint16 port)
 Sets the port on the local side of a connection to port. More...
 
void setPeerAddress (const QHostAddress &address)
 Sets the address of the remote side of the connection to address. More...
 
void setPeerName (const QString &name)
 Sets the host name of the remote peer to name. More...
 
void setPeerPort (quint16 port)
 Sets the port of the remote side of the connection to port. More...
 
void setSocketError (SocketError socketError)
 Sets the type of error that last occurred to socketError. More...
 
void setSocketState (SocketState state)
 Sets the state of the socket to state. More...
 
qint64 writeData (const char *data, qint64 len)
 Reimplemented Function More...
 
- Protected Functions inherited from QIODevice
 QIODevice (QIODevicePrivate &dd, QObject *parent=0)
 
void setErrorString (const QString &errorString)
 Sets the human readable description of the last device error that occurred to str. More...
 
void setOpenMode (OpenMode openMode)
 Sets the OpenMode of the device to openMode. More...
 
- Protected Functions inherited from QObject
virtual void childEvent (QChildEvent *)
 This event handler can be reimplemented in a subclass to receive child events. More...
 
virtual void connectNotify (const char *signal)
 This virtual function is called when something has been connected to signal in this object. More...
 
virtual void customEvent (QEvent *)
 This event handler can be reimplemented in a subclass to receive custom events. More...
 
virtual void disconnectNotify (const char *signal)
 This virtual function is called when something has been disconnected from signal in this object. More...
 
 QObject (QObjectPrivate &dd, QObject *parent=0)
 
int receivers (const char *signal) const
 Returns the number of receivers connected to the signal. More...
 
QObjectsender () const
 Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns 0. More...
 
int senderSignalIndex () const
 
virtual void timerEvent (QTimerEvent *)
 This event handler can be reimplemented in a subclass to receive timer events for the object. More...
 

Additional Inherited Members

- Public Slots inherited from QObject
void deleteLater ()
 Schedules this object for deletion. More...
 
- Static Public Functions inherited from QObject
static bool connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
 Creates a connection of the given type from the signal in the sender object to the method in the receiver object. More...
 
static bool connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member)
 Disconnects signal in object sender from method in object receiver. More...
 
static bool disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member)
 
static uint registerUserData ()
 
static QString tr (const char *sourceText, const char *comment=0, int n=-1)
 
static QString trUtf8 (const char *sourceText, const char *comment=0, int n=-1)
 
- Static Public Variables inherited from QObject
static const QMetaObject staticMetaObject
 This variable stores the meta-object for the class. More...
 
- Protected Variables inherited from QObject
QScopedPointer< QObjectDatad_ptr
 
- Static Protected Variables inherited from QObject
static const QMetaObject staticQtMetaObject
 

Detailed Description

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

Note
This class or function is reentrant.
Attention
Module: 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:

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, error() 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 (i.e., when the client has read the data). 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::ClosedState, 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 error(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:

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 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 network/fortuneclient and network/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
QFtp, QNetworkAccessManager, QTcpServer

Definition at line 64 of file qabstractsocket.h.

Enumerations

◆ NetworkLayerProtocol

This enum describes the network layer protocol values used in Qt.

  • IPv4Protocol IPv4
  • IPv6Protocol IPv6
  • UnknownNetworkLayerProtocol Other than IPv4 and IPv6
See also
QHostAddress::protocol()
Enumerator
IPv4Protocol 
IPv6Protocol 
UnknownNetworkLayerProtocol 

Definition at line 74 of file qabstractsocket.h.

◆ SocketError

This enum describes the socket errors that can occur.

  • ConnectionRefusedError The connection was refused by the peer (or timed out).
  • 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.
  • HostNotFoundError The host address was not found.
  • SocketAccessError The socket operation failed because the application lacked the required privileges.
  • SocketResourceError The local system ran out of resources (e.g., too many sockets).
  • SocketTimeoutError The socket operation timed out.
  • DatagramTooLargeError The datagram was larger than the operating system's limit (which can be as low as 8192 bytes).
  • NetworkError An error occurred with the network (e.g., the network cable was accidentally plugged out).
  • AddressInUseError The address specified to QUdpSocket::bind() is already in use and was set to be exclusive.
  • SocketAddressNotAvailableError The address specified to QUdpSocket::bind() does not belong to the host.
  • UnsupportedSocketOperationError The requested socket operation is not supported by the local operating system (e.g., lack of IPv6 support).
  • ProxyAuthenticationRequiredError The socket is using a proxy, and the proxy requires authentication.
  • SslHandshakeFailedError The SSL/TLS handshake failed, so the connection was closed (only used in QSslSocket) (This value was introduced in 4.4.)
  • UnfinishedSocketOperationError Used by QAbstractSocketEngine only, The last operation attempted has not finished yet (still in progress in the background). (This value was introduced in 4.4.)
  • ProxyConnectionRefusedError Could not contact the proxy server because the connection to that server was denied (This value was introduced in 4.5.)
  • ProxyConnectionClosedError The connection to the proxy server was closed unexpectedly (before the connection to the final peer was established) (This value was introduced in 4.5.)
  • ProxyConnectionTimeoutError The connection to the proxy server timed out or the proxy server stopped responding in the authentication phase. (This value was introduced in 4.5.)
  • ProxyNotFoundError The proxy address set with setProxy() (or the application proxy) was not found. (This value was introduced in 4.5.)
  • ProxyProtocolError The connection negotiation with the proxy server because the response from the proxy server could not be understood. (This value was introduced in 4.5.)
Enumerator
ConnectionRefusedError 
RemoteHostClosedError 
HostNotFoundError 
SocketAccessError 
SocketResourceError 
SocketTimeoutError 
DatagramTooLargeError 
NetworkError 
AddressInUseError 
SocketAddressNotAvailableError 
UnsupportedSocketOperationError 
UnfinishedSocketOperationError 
ProxyAuthenticationRequiredError 
SslHandshakeFailedError 
ProxyConnectionRefusedError 
ProxyConnectionClosedError 
ProxyConnectionTimeoutError 
ProxyNotFoundError 
ProxyProtocolError 
UnknownSocketError 

Definition at line 79 of file qabstractsocket.h.

79  {
85  SocketTimeoutError, /* 5 */
99 
100  UnknownSocketError = -1
101  };

◆ SocketOption

This enum represents the options that can be set on a socket.

Since
4.6

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.

  • 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.
  • KeepAliveOption Set this to 1 to enable the SO_KEEPALIVE socket option
  • MulticastTtlOption Set this to an integer value to set IP_MULTICAST_TTL (TTL for multicast datagrams) socket option.
  • MulticastLoopbackOption Set this to 1 to enable the IP_MULTICAST_LOOP (multicast loopback) socket option.
See also
QAbstractSocket::setSocketOption(), QAbstractSocket::socketOption()
Enumerator
LowDelayOption 
KeepAliveOption 
MulticastTtlOption 
MulticastLoopbackOption 

Definition at line 120 of file qabstractsocket.h.

◆ SocketState

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

  • UnconnectedState The socket is not connected.
  • HostLookupState The socket is performing a host name lookup.
  • ConnectingState The socket has started establishing a connection.
  • ConnectedState A connection is established.
  • BoundState The socket is bound to an address and port (for servers).
  • ClosingState The socket is about to close (data may still be waiting to be written).
  • ListeningState For internal use only.
  • Idle
  • HostLookup
  • Connecting
  • Connected
  • Closing
  • Connection
See also
QAbstractSocket::state()
Enumerator
UnconnectedState 
HostLookupState 
ConnectingState 
ConnectedState 
BoundState 
ListeningState 
ClosingState 

Definition at line 102 of file qabstractsocket.h.

◆ SocketType

This enum describes the transport layer protocol.

  • TcpSocket TCP
  • UdpSocket UDP
  • UnknownSocketType Other than TCP and UDP
See also
QAbstractSocket::socketType()
Enumerator
TcpSocket 
UdpSocket 
UnknownSocketType 

Definition at line 69 of file qabstractsocket.h.

Constructors and Destructors

◆ 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 1351 of file qabstractsocket.cpp.

1352  : QIODevice(*new QAbstractSocketPrivate, parent)
1353 {
1355 #if defined(QABSTRACTSOCKET_DEBUG)
1356  qDebug("QAbstractSocket::QAbstractSocket(%p)", parent);
1357 #endif
1358  d->socketType = socketType;
1359 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
SocketType socketType() const
Returns the socket type (TCP, UDP, or other).
Q_CORE_EXPORT void qDebug(const char *,...)
QIODevice()
Constructs a QIODevice object.
Definition: qiodevice.cpp:390
The QAbstractSocket class provides the base functionality common to all socket types.

◆ ~QAbstractSocket()

QAbstractSocket::~QAbstractSocket ( )
virtual

Destroys the socket.

Definition at line 1364 of file qabstractsocket.cpp.

1365 {
1367 #if defined(QABSTRACTSOCKET_DEBUG)
1368  qDebug("QAbstractSocket::~QAbstractSocket()");
1369 #endif
1370  if (d->state != UnconnectedState)
1371  abort();
1372 }
double d
Definition: qnumeric_p.h:62
void abort()
Aborts the current connection and resets the socket.
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
The QAbstractSocket class provides the base functionality common to all socket types.

◆ QAbstractSocket() [2/2]

QAbstractSocket::QAbstractSocket ( SocketType  socketType,
QAbstractSocketPrivate dd,
QObject parent = 0 
)
protected

Constructs a new abstract socket of type socketType.

Warning
This function is not part of the public interface.

The parent argument is passed to QObject's constructor.

Definition at line 1332 of file qabstractsocket.cpp.

1334  : QIODevice(dd, parent)
1335 {
1337 #if defined(QABSTRACTSOCKET_DEBUG)
1338  qDebug("QAbstractSocket::QAbstractSocket(%sSocket, QAbstractSocketPrivate == %p, parent == %p)",
1339  socketType == TcpSocket ? "Tcp" : socketType == UdpSocket
1340  ? "Udp" : "Unknown", &dd, parent);
1341 #endif
1342  d->socketType = socketType;
1343 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
SocketType socketType() const
Returns the socket type (TCP, UDP, or other).
Q_CORE_EXPORT void qDebug(const char *,...)
QIODevice()
Constructs a QIODevice object.
Definition: qiodevice.cpp:390
The QAbstractSocket class provides the base functionality common to all socket types.

Functions

◆ 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 2151 of file qabstractsocket.cpp.

Referenced by QHttpPrivate::_q_slotError(), QHttpPrivate::_q_slotSendRequest(), QFtpDTP::abortConnection(), QSocks5SocketEnginePrivate::reauthenticate(), and ~QAbstractSocket().

2152 {
2154 #if defined (QABSTRACTSOCKET_DEBUG)
2155  qDebug("QAbstractSocket::abort()");
2156 #endif
2157  if (d->state == UnconnectedState)
2158  return;
2159 #ifndef QT_NO_OPENSSL
2160  if (QSslSocket *socket = qobject_cast<QSslSocket *>(this)) {
2161  socket->abort();
2162  return;
2163  }
2164 #endif
2165  if (d->connectTimer) {
2166  d->connectTimer->stop();
2167  delete d->connectTimer;
2168  d->connectTimer = 0;
2169  }
2170 
2171  d->writeBuffer.clear();
2172  d->abortCalled = true;
2173  close();
2174 }
double d
Definition: qnumeric_p.h:62
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
void close()
Closes the I/O device for the socket, disconnects the socket&#39;s connection with the host...
The QAbstractSocket class provides the base functionality common to all socket types.

◆ atEnd()

bool QAbstractSocket::atEnd ( ) const
virtual

Returns true if no more data is currently available for reading; otherwise returns false.

Reimplemented Function

This function is most commonly used when reading data from the socket in a loop. For example:

 // This slot is connected to QAbstractSocket::readyRead()
 void SocketClass::readyReadSlot()
 {
     while (!socket.atEnd()) {
         QByteArray data = socket.read(100);
         ....
     }
 }
See also
bytesAvailable(), readyRead()

Reimplemented from QIODevice.

Reimplemented in QSslSocket.

Definition at line 2198 of file qabstractsocket.cpp.

2199 {
2200  return QIODevice::atEnd() && (!isOpen() || d_func()->readBuffer.isEmpty());
2201 }
virtual bool atEnd() const
Returns true if the current read and write position is at the end of the device (i.e.
Definition: qiodevice.cpp:711
bool isOpen() const
Returns true if the device is open; otherwise returns false.
Definition: qiodevice.cpp:530

◆ bytesAvailable()

qint64 QAbstractSocket::bytesAvailable ( ) const
virtual

Returns the number of incoming bytes that are waiting to be read.

See also
bytesToWrite(), read()

Reimplemented from QIODevice.

Reimplemented in QSslSocket.

Definition at line 1558 of file qabstractsocket.cpp.

Referenced by QHttpNetworkConnectionChannel::_q_error(), QHttpNetworkConnectionChannel::_q_readyRead(), QSslSocketPrivate::_q_readyReadSlot(), QHttpNetworkConnectionChannel::_q_receiveReply(), QHttpPrivate::_q_slotReadyRead(), QFtpDTP::abortConnection(), QHttpNetworkConnectionChannel::allDone(), QFtpDTP::bytesAvailable(), QVNCServer::clientCutText(), QSocks5PasswordAuthenticator::continueAuthenticate(), QSslSocketBackendPrivate::disconnected(), QHttpNetworkReplyPrivate::getChunkSize(), QSocks5SocketEnginePrivate::parseAuthenticationMethodReply(), QRfbSetEncodings::read(), QRfbFrameBufferUpdateRequest::read(), QRfbKeyEvent::read(), QRfbPointerEvent::read(), QRfbClientCutText::read(), QHttpNetworkReplyPrivate::readBody(), QHttpNetworkReplyPrivate::readBodyFast(), QVNCServer::readClient(), QHttpNetworkReplyPrivate::readReplyBodyChunked(), QHttpNetworkReplyPrivate::readReplyBodyRaw(), QHttpNetworkConnectionChannel::sendRequest(), QVNCServer::setEncodings(), QVNCServer::setPixelFormat(), QFtpDTP::socketReadyRead(), and QSslSocketBackendPrivate::transmit().

1559 {
1560  Q_D(const QAbstractSocket);
1561  qint64 available = QIODevice::bytesAvailable();
1562 
1563  available += (qint64) d->readBuffer.size();
1564 
1565  if (!d->isBuffered && d->socketEngine && d->socketEngine->isValid())
1566  available += d->socketEngine->bytesAvailable();
1567 
1568 #if defined(QABSTRACTSOCKET_DEBUG)
1569  qDebug("QAbstractSocket::bytesAvailable() == %llu", available);
1570 #endif
1571  return available;
1572 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
__int64 qint64
Definition: qglobal.h:942
virtual qint64 bytesAvailable() const
Returns the number of bytes that are available for reading.
Definition: qiodevice.cpp:752
The QAbstractSocket class provides the base functionality common to all socket types.

◆ bytesToWrite()

qint64 QAbstractSocket::bytesToWrite ( ) const
virtual

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 1544 of file qabstractsocket.cpp.

Referenced by QHttpPrivate::postMoreData(), QHttpNetworkConnectionChannel::sendRequest(), and QFtpDTP::writeData().

1545 {
1546  Q_D(const QAbstractSocket);
1547 #if defined(QABSTRACTSOCKET_DEBUG)
1548  qDebug("QAbstractSocket::bytesToWrite() == %i", d->writeBuffer.size());
1549 #endif
1550  return (qint64)d->writeBuffer.size();
1551 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
__int64 qint64
Definition: qglobal.h:942
The QAbstractSocket class provides the base functionality common to all socket types.

◆ canReadLine()

bool QAbstractSocket::canReadLine ( ) const
virtual

Returns true if a line of data can be read from the socket; otherwise returns false.

See also
readLine()

Reimplemented from QIODevice.

Reimplemented in QSslSocket.

Definition at line 1644 of file qabstractsocket.cpp.

Referenced by QHttpPrivate::_q_slotReadyRead(), QFtpPI::readyRead(), and QFtpDTP::socketReadyRead().

1645 {
1646  bool hasLine = d_func()->readBuffer.canReadLine();
1647 #if defined (QABSTRACTSOCKET_DEBUG)
1648  qDebug("QAbstractSocket::canReadLine() == %s, buffer size = %d, size = %d", hasLine ? "true" : "false",
1649  d_func()->readBuffer.size(), d_func()->buffer.size());
1650 #endif
1651  return hasLine || QIODevice::canReadLine();
1652 }
Q_CORE_EXPORT void qDebug(const char *,...)
virtual bool canReadLine() const
Returns true if a complete line of data can be read from the device; otherwise returns false...
Definition: qiodevice.cpp:1330

◆ close()

void QAbstractSocket::close ( )
virtual

Closes the I/O device for the socket, disconnects the socket's connection with the host, closes the socket, and resets the name, address, port number and underlying socket descriptor.

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 QSslSocket.

Definition at line 2550 of file qabstractsocket.cpp.

Referenced by QHttpPrivate::_q_slotReadyRead(), abort(), QSslSocket::close(), QHttpNetworkConnectionChannel::close(), QHttpPrivate::closeConn(), QFtpPI::connectionClosed(), QSocks5PasswordAuthenticator::continueAuthenticate(), QSocks5SocketEnginePrivate::parseAuthenticationMethodReply(), QSocks5SocketEnginePrivate::parseRequestMethodReply(), QSocks5SocketEnginePrivate::reauthenticate(), QFtpDTP::socketReadyRead(), waitForBytesWritten(), waitForDisconnected(), waitForReadyRead(), QFtpDTP::writeData(), and QHttpNetworkConnectionPrivate::~QHttpNetworkConnectionPrivate().

2551 {
2553 #if defined(QABSTRACTSOCKET_DEBUG)
2554  qDebug("QAbstractSocket::close()");
2555 #endif
2556  QIODevice::close();
2557  if (d->state != UnconnectedState) {
2558  d->closeCalled = true;
2560  }
2561 
2562  d->localPort = 0;
2563  d->peerPort = 0;
2564  d->localAddress.clear();
2565  d->peerAddress.clear();
2566  d->peerName.clear();
2567  d->cachedSocketDescriptor = -1;
2568 }
double d
Definition: qnumeric_p.h:62
virtual void close()
First emits aboutToClose(), then closes the device and sets its OpenMode to NotOpen.
Definition: qiodevice.cpp:590
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
void disconnectFromHost()
Attempts to close the socket.
The QAbstractSocket class provides the base functionality common to all socket types.

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

◆ connectToHost() [1/2]

void QAbstractSocket::connectToHost ( const QString hostName,
quint16  port,
OpenMode  openMode = ReadWrite 
)

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

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

Definition at line 1409 of file qabstractsocket.cpp.

Referenced by QHttpPrivate::_q_slotSendRequest(), QFtpDTP::connectToHost(), connectToHost(), QFtpPI::connectToHost(), QHttpNetworkConnectionChannel::ensureConnection(), and QSocks5SocketEnginePrivate::reauthenticate().

1411 {
1412  QMetaObject::invokeMethod(this, "connectToHostImplementation",
1414  Q_ARG(QString, hostName),
1415  Q_ARG(quint16, port),
1416  Q_ARG(OpenMode, openMode));
1417 }
#define Q_ARG(type, data)
Definition: qobjectdefs.h:246
The QString class provides a Unicode character string.
Definition: qstring.h:83
unsigned short quint16
Definition: qglobal.h:936
OpenMode openMode() const
Returns the mode in which the device has been opened; i.e.
Definition: qiodevice.cpp:465
static bool invokeMethod(QObject *obj, const char *member, Qt::ConnectionType, QGenericReturnArgument ret, QGenericArgument val0=QGenericArgument(0), QGenericArgument val1=QGenericArgument(), QGenericArgument val2=QGenericArgument(), QGenericArgument val3=QGenericArgument(), QGenericArgument val4=QGenericArgument(), QGenericArgument val5=QGenericArgument(), QGenericArgument val6=QGenericArgument(), QGenericArgument val7=QGenericArgument(), QGenericArgument val8=QGenericArgument(), QGenericArgument val9=QGenericArgument())
Invokes the member (a signal or a slot name) on the object obj.

◆ connectToHost() [2/2]

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

Attempts to make a connection to address on port port.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 1527 of file qabstractsocket.cpp.

1529 {
1530 #if defined(QABSTRACTSOCKET_DEBUG)
1531  qDebug("QAbstractSocket::connectToHost([%s], %i, %i)...",
1532  address.toString().toLatin1().constData(), port, (int) openMode);
1533 #endif
1534  connectToHost(address.toString(), port, openMode);
1535 }
void connectToHost(const QString &hostName, quint16 port, OpenMode mode=ReadWrite)
Attempts to make a connection to hostName on the given port.
Q_CORE_EXPORT void qDebug(const char *,...)
QString toString() const
Returns the address as a string.
QByteArray toLatin1() const Q_REQUIRED_RESULT
Returns a Latin-1 representation of the string as a QByteArray.
Definition: qstring.cpp:3993
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
OpenMode openMode() const
Returns the mode in which the device has been opened; i.e.
Definition: qiodevice.cpp:465

◆ connectToHostImplementation

void QAbstractSocket::connectToHostImplementation ( const QString hostName,
quint16  port,
OpenMode  openMode = ReadWrite 
)
protectedslot

Contains the implementation of connectToHost().

Since
4.1

Attempts to make a connection to hostName on the given port. The socket is opened in the given openMode.

Definition at line 1430 of file qabstractsocket.cpp.

1432 {
1434 #if defined(QABSTRACTSOCKET_DEBUG)
1435  qDebug("QAbstractSocket::connectToHost(\"%s\", %i, %i)...", qPrintable(hostName), port,
1436  (int) openMode);
1437 #endif
1438 
1439  if (d->state == ConnectedState || d->state == ConnectingState
1440  || d->state == ClosingState || d->state == HostLookupState) {
1441  qWarning("QAbstractSocket::connectToHost() called when already looking up or connecting/connected to \"%s\"", qPrintable(hostName));
1442  return;
1443  }
1444 
1445  d->hostName = hostName;
1446  d->port = port;
1447  d->state = UnconnectedState;
1448  d->readBuffer.clear();
1449  d->writeBuffer.clear();
1450  d->abortCalled = false;
1451  d->closeCalled = false;
1452  d->pendingClose = false;
1453  d->localPort = 0;
1454  d->peerPort = 0;
1455  d->localAddress.clear();
1456  d->peerAddress.clear();
1457  d->peerName = hostName;
1458  if (d->hostLookupId != -1) {
1459  QHostInfo::abortHostLookup(d->hostLookupId);
1460  d->hostLookupId = -1;
1461  }
1462 
1463 #ifndef QT_NO_NETWORKPROXY
1464  // Get the proxy information
1465  d->resolveProxy(hostName, port);
1466  if (d->proxyInUse.type() == QNetworkProxy::DefaultProxy) {
1467  // failed to setup the proxy
1469  setErrorString(QAbstractSocket::tr("Operation on socket is not supported"));
1470  emit error(d->socketError);
1471  return;
1472  }
1473 #endif
1474 
1476  d->isBuffered = false; // Unbuffered QTcpSocket
1477  else if (!d_func()->isBuffered)
1478  openMode |= QAbstractSocket::Unbuffered; // QUdpSocket
1479 
1481  d->state = HostLookupState;
1482  emit stateChanged(d->state);
1483 
1484  QHostAddress temp;
1485  if (temp.setAddress(hostName)) {
1486  QHostInfo info;
1487  info.setAddresses(QList<QHostAddress>() << temp);
1488  d->_q_startConnecting(info);
1489 #ifndef QT_NO_NETWORKPROXY
1490  } else if (d->proxyInUse.capabilities() & QNetworkProxy::HostNameLookupCapability) {
1491  // the proxy supports connection by name, so use it
1492  d->startConnectingByName(hostName);
1493  return;
1494 #endif
1495  } else {
1496  if (d->threadData->eventDispatcher) {
1497  // this internal API for QHostInfo either immediately gives us the desired
1498  // QHostInfo from cache or later calls the _q_startConnecting slot.
1499  bool immediateResultValid = false;
1500  QHostInfo hostInfo = qt_qhostinfo_lookup(hostName,
1501  this,
1502  SLOT(_q_startConnecting(QHostInfo)),
1503  &immediateResultValid,
1504  &d->hostLookupId);
1505  if (immediateResultValid) {
1506  d->hostLookupId = -1;
1507  d->_q_startConnecting(hostInfo);
1508  }
1509  }
1510  }
1511 
1512 #if defined(QABSTRACTSOCKET_DEBUG)
1513  qDebug("QAbstractSocket::connectToHost(\"%s\", %i) == %s%s", hostName.toLatin1().constData(), port,
1514  (d->state == ConnectedState) ? "true" : "false",
1515  (d->state == ConnectingState || d->state == HostLookupState)
1516  ? " (connection in progress)" : "");
1517 #endif
1518 }
double d
Definition: qnumeric_p.h:62
static mach_timebase_info_data_t info
#define SLOT(a)
Definition: qobjectdefs.h:226
static void abortHostLookup(int lookupId)
Aborts the host lookup with the ID id, as returned by lookupHost().
Definition: qhostinfo.cpp:255
static QString tr(const char *sourceText, const char *comment=0, int n=-1)
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
void setAddresses(const QList< QHostAddress > &addresses)
Sets the list of addresses in this QHostInfo to addresses.
Definition: qhostinfo.cpp:382
#define emit
Definition: qobjectdefs.h:76
Q_CORE_EXPORT void qWarning(const char *,...)
The QHostInfo class provides static functions for host name lookups.
Definition: qhostinfo.h:58
QByteArray toLatin1() const Q_REQUIRED_RESULT
Returns a Latin-1 representation of the string as a QByteArray.
Definition: qstring.cpp:3993
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
void setAddress(quint32 ip4Addr)
Set the IPv4 address specified by ip4Addr.
OpenMode openMode() const
Returns the mode in which the device has been opened; i.e.
Definition: qiodevice.cpp:465
void setErrorString(const QString &errorString)
Sets the human readable description of the last device error that occurred to str.
Definition: qiodevice.cpp:1660
virtual bool open(OpenMode mode)
Opens the device and sets its OpenMode to mode.
Definition: qiodevice.cpp:570
void stateChanged(QAbstractSocket::SocketState)
This signal is emitted whenever QAbstractSocket&#39;s state changes.
The QHostAddress class provides an IP address.
Definition: qhostaddress.h:70
SocketError error() const
Returns the type of error that last occurred.
#define qPrintable(string)
Definition: qglobal.h:1750
The QAbstractSocket class provides the base functionality common to all socket types.
QHostInfo qt_qhostinfo_lookup(const QString &name, QObject *receiver, const char *member, bool *valid, int *id)
Definition: qhostinfo.cpp:726

◆ 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 deleteLater() function.
See also
connectToHost(), disconnectFromHost(), abort()

Referenced by disconnectFromHostImplementation().

◆ disconnectFromHost()

void QAbstractSocket::disconnectFromHost ( )

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

Definition at line 2578 of file qabstractsocket.cpp.

Referenced by close(), QSslSocketBackendPrivate::disconnectFromHost(), QSslSocketBackendPrivate::startHandshake(), and waitForConnected().

2579 {
2580  QMetaObject::invokeMethod(this, "disconnectFromHostImplementation",
2582 }
static bool invokeMethod(QObject *obj, const char *member, Qt::ConnectionType, QGenericReturnArgument ret, QGenericArgument val0=QGenericArgument(0), QGenericArgument val1=QGenericArgument(), QGenericArgument val2=QGenericArgument(), QGenericArgument val3=QGenericArgument(), QGenericArgument val4=QGenericArgument(), QGenericArgument val5=QGenericArgument(), QGenericArgument val6=QGenericArgument(), QGenericArgument val7=QGenericArgument(), QGenericArgument val8=QGenericArgument(), QGenericArgument val9=QGenericArgument())
Invokes the member (a signal or a slot name) on the object obj.

◆ disconnectFromHostImplementation

void QAbstractSocket::disconnectFromHostImplementation ( )
protectedslot

Contains the implementation of disconnectFromHost().

Since
4.1

Definition at line 2592 of file qabstractsocket.cpp.

2593 {
2595 #if defined(QABSTRACTSOCKET_DEBUG)
2596  qDebug("QAbstractSocket::disconnectFromHost()");
2597 #endif
2598 
2599  if (d->state == UnconnectedState) {
2600 #if defined(QABSTRACTSOCKET_DEBUG)
2601  qDebug("QAbstractSocket::disconnectFromHost() was called on an unconnected socket");
2602 #endif
2603  return;
2604  }
2605 
2606  if (!d->abortCalled && (d->state == ConnectingState || d->state == HostLookupState)) {
2607 #if defined(QABSTRACTSOCKET_DEBUG)
2608  qDebug("QAbstractSocket::disconnectFromHost() but we're still connecting");
2609 #endif
2610  d->pendingClose = true;
2611  return;
2612  }
2613 
2614 #ifdef QT3_SUPPORT
2615  emit connectionClosed(); // compat signal
2616 #endif
2617 
2618  // Disable and delete read notification
2619  if (d->socketEngine)
2620  d->socketEngine->setReadNotificationEnabled(false);
2621 
2622  if (d->abortCalled) {
2623 #if defined(QABSTRACTSOCKET_DEBUG)
2624  qDebug("QAbstractSocket::disconnectFromHost() aborting immediately");
2625 #endif
2626  if (d->state == HostLookupState) {
2627  QHostInfo::abortHostLookup(d->hostLookupId);
2628  d->hostLookupId = -1;
2629  }
2630  } else {
2631  // Perhaps emit closing()
2632  if (d->state != ClosingState) {
2633  d->state = ClosingState;
2634 #if defined(QABSTRACTSOCKET_DEBUG)
2635  qDebug("QAbstractSocket::disconnectFromHost() emits stateChanged()(ClosingState)");
2636 #endif
2637  emit stateChanged(d->state);
2638  } else {
2639 #if defined(QABSTRACTSOCKET_DEBUG)
2640  qDebug("QAbstractSocket::disconnectFromHost() return from delayed close");
2641 #endif
2642  }
2643 
2644  // Wait for pending data to be written.
2645  if (d->socketEngine && d->socketEngine->isValid() && (d->writeBuffer.size() > 0
2646  || d->socketEngine->bytesToWrite() > 0)) {
2647  // hack: when we are waiting for the socket engine to write bytes (only
2648  // possible when using Socks5 or HTTP socket engine), then close
2649  // anyway after 2 seconds. This is to prevent a timeout on Mac, where we
2650  // sometimes just did not get the write notifier from the underlying
2651  // CFSocket and no progress was made.
2652  if (d->writeBuffer.size() == 0 && d->socketEngine->bytesToWrite() > 0) {
2653  if (!d->disconnectTimer) {
2654  d->disconnectTimer = new QTimer(this);
2655  connect(d->disconnectTimer, SIGNAL(timeout()), this,
2656  SLOT(_q_forceDisconnect()), Qt::DirectConnection);
2657  }
2658  if (!d->disconnectTimer->isActive())
2659  d->disconnectTimer->start(2000);
2660  }
2661  d->socketEngine->setWriteNotificationEnabled(true);
2662 
2663 #if defined(QABSTRACTSOCKET_DEBUG)
2664  qDebug("QAbstractSocket::disconnectFromHost() delaying disconnect");
2665 #endif
2666  return;
2667  } else {
2668 #if defined(QABSTRACTSOCKET_DEBUG)
2669  qDebug("QAbstractSocket::disconnectFromHost() disconnecting immediately");
2670 #endif
2671  }
2672  }
2673 
2674  SocketState previousState = d->state;
2675  d->resetSocketLayer();
2676  d->state = UnconnectedState;
2677  emit stateChanged(d->state);
2678  emit readChannelFinished(); // we got an EOF
2679 
2680 #ifdef QT3_SUPPORT
2681  emit delayedCloseFinished(); // compat signal
2682 #endif
2683  // only emit disconnected if we were connected before
2684  if (previousState == ConnectedState || previousState == ClosingState)
2685  emit disconnected();
2686 
2687  d->localPort = 0;
2688  d->peerPort = 0;
2689  d->localAddress.clear();
2690  d->peerAddress.clear();
2691 
2692 #if defined(QABSTRACTSOCKET_DEBUG)
2693  qDebug("QAbstractSocket::disconnectFromHost() disconnected!");
2694 #endif
2695 
2696  if (d->closeCalled) {
2697 #if defined(QABSTRACTSOCKET_DEBUG)
2698  qDebug("QAbstractSocket::disconnectFromHost() closed!");
2699 #endif
2700  d->readBuffer.clear();
2701  d->writeBuffer.clear();
2702  QIODevice::close();
2703  }
2704 }
double d
Definition: qnumeric_p.h:62
virtual void close()
First emits aboutToClose(), then closes the device and sets its OpenMode to NotOpen.
Definition: qiodevice.cpp:590
void readChannelFinished()
This signal is emitted when the input (reading) stream is closed in this device.
#define SLOT(a)
Definition: qobjectdefs.h:226
static void abortHostLookup(int lookupId)
Aborts the host lookup with the ID id, as returned by lookupHost().
Definition: qhostinfo.cpp:255
void disconnected()
This signal is emitted when the socket has been disconnected.
#define Q_D(Class)
Definition: qglobal.h:2482
SocketState
This enum describes the different states in which a socket can be.
Q_CORE_EXPORT void qDebug(const char *,...)
#define SIGNAL(a)
Definition: qobjectdefs.h:227
static bool connect(const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
Creates a connection of the given type from the signal in the sender object to the method in the rece...
Definition: qobject.cpp:2580
#define emit
Definition: qobjectdefs.h:76
void stateChanged(QAbstractSocket::SocketState)
This signal is emitted whenever QAbstractSocket&#39;s state changes.
The QTimer class provides repetitive and single-shot timers.
Definition: qtimer.h:56
The QAbstractSocket class provides the base functionality common to all socket types.

◆ error() [1/2]

QAbstractSocket::SocketError QAbstractSocket::error ( ) const

◆ error [2/2]

void QAbstractSocket::error ( QAbstractSocket::SocketError  socketError)
signal

This signal is emitted after an error occurred.

The socketError parameter describes the type of error that occurred.

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}

◆ 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 2218 of file qabstractsocket.cpp.

Referenced by QDeclarativeDebugConnectionPrivate::advertisePlugins(), QDeclarativeDebugConnectionPrivate::connected(), QVNCDirtyMap::QVNCDirtyMap(), QSocks5SocketEnginePrivate::sendRequestMethod(), QRfbRawEncoder::write(), and QRfbHextileEncoder< SRC >::write().

2219 {
2221 #ifndef QT_NO_OPENSSL
2222  // Manual polymorphism; flush() isn't virtual, but QSslSocket overloads
2223  // it.
2224  if (QSslSocket *socket = qobject_cast<QSslSocket *>(this))
2225  return socket->flush();
2226 #endif
2227  Q_CHECK_SOCKETENGINE(false);
2228  return d->flush();
2229 }
double d
Definition: qnumeric_p.h:62
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define Q_CHECK_SOCKETENGINE(returnValue)
The QAbstractSocket class provides the base functionality common to all socket types.

◆ 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
virtual

Reimplemented Function

Reimplemented from QIODevice.

Definition at line 2178 of file qabstractsocket.cpp.

2179 {
2180  return true;
2181 }

◆ 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 1383 of file qabstractsocket.cpp.

Referenced by QUdpSocket::setMulticastInterface(), and QSslSocketBackendPrivate::transmit().

1384 {
1385  return d_func()->socketEngine ? d_func()->socketEngine->isValid() : isOpen();
1386 }
bool isOpen() const
Returns true if the device is open; otherwise returns false.
Definition: qiodevice.cpp:530

◆ 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 1596 of file qabstractsocket.cpp.

Referenced by QSslSocketPrivate::_q_connectedSlot(), and QFtpPI::startNextCmd().

1597 {
1598  Q_D(const QAbstractSocket);
1599  return d->localAddress;
1600 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QAbstractSocket class provides the base functionality common to all socket types.

◆ 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 1580 of file qabstractsocket.cpp.

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

1581 {
1582  Q_D(const QAbstractSocket);
1583  return d->localPort;
1584 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QAbstractSocket class provides the base functionality common to all socket types.

◆ 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 1620 of file qabstractsocket.cpp.

Referenced by QSslSocketPrivate::_q_connectedSlot(), and QFtpPI::processReply().

1621 {
1622  Q_D(const QAbstractSocket);
1623  return d->peerAddress;
1624 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QAbstractSocket class provides the base functionality common to all socket types.

◆ 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 1632 of file qabstractsocket.cpp.

Referenced by QSslSocketPrivate::_q_connectedSlot(), QHttpPrivate::_q_slotError(), QHttpPrivate::_q_slotSendRequest(), QFtpPI::error(), QHttpNetworkConnectionPrivate::errorDetail(), and QFtpPI::processReply().

1633 {
1634  Q_D(const QAbstractSocket);
1635  return d->peerName.isEmpty() ? d->hostName : d->peerName;
1636 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QAbstractSocket class provides the base functionality common to all socket types.

◆ 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 1608 of file qabstractsocket.cpp.

Referenced by QSslSocketPrivate::_q_connectedSlot(), and QHttpPrivate::_q_slotSendRequest().

1609 {
1610  Q_D(const QAbstractSocket);
1611  return d->peerPort;
1612 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QAbstractSocket class provides the base functionality common to all socket types.

◆ proxy()

QNetworkProxy QAbstractSocket::proxy ( ) const

Returns the network proxy for this socket.

Since
4.1

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 2859 of file qabstractsocket.cpp.

Referenced by QHttpNetworkConnectionChannel::ensureConnection().

2860 {
2861  Q_D(const QAbstractSocket);
2862  return d->proxy;
2863 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QAbstractSocket class provides the base functionality common to all socket types.

◆ 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

◆ 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 2716 of file qabstractsocket.cpp.

2717 {
2718  return d_func()->readBufferMaxSize;
2719 }

◆ readData()

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

Reimplemented Function

Implements QIODevice.

Reimplemented in QSslSocket.

Definition at line 2233 of file qabstractsocket.cpp.

2234 {
2236 
2237  // This is for a buffered QTcpSocket
2238  if (d->isBuffered && d->readBuffer.isEmpty())
2239  // if we're still connected, return 0 indicating there may be more data in the future
2240  // if we're not connected, return -1 indicating EOF
2241  return d->state == QAbstractSocket::ConnectedState ? qint64(0) : qint64(-1);
2242 
2243  // short cut for a char read if we have something in the buffer
2244  if (maxSize == 1 && !d->readBuffer.isEmpty()) {
2245  *data = d->readBuffer.getChar();
2246 #if defined (QABSTRACTSOCKET_DEBUG)
2247  qDebug("QAbstractSocket::readData(%p '%c (0x%.2x)', 1) == 1 [char buffer]",
2248  data, isprint(int(uchar(*data))) ? *data : '?', *data);
2249 #endif
2250  if (d->readBuffer.isEmpty() && d->socketEngine && d->socketEngine->isValid())
2251  d->socketEngine->setReadNotificationEnabled(true);
2252  return 1;
2253  }
2254 
2255  // Special case for an Unbuffered QTcpSocket
2256  // Re-filling the buffer.
2257  if (d->socketType == TcpSocket
2258  && !d->isBuffered
2259  && d->readBuffer.size() < maxSize
2260  && d->readBufferMaxSize > 0
2261  && maxSize < d->readBufferMaxSize
2262  && d->socketEngine
2263  && d->socketEngine->isValid()) {
2264  // Our buffer is empty and a read() was requested for a byte amount that is smaller
2265  // than the readBufferMaxSize. This means that we should fill our buffer since we want
2266  // such small reads come from the buffer and not always go to the costly socket engine read()
2267  qint64 bytesToRead = d->socketEngine->bytesAvailable();
2268  if (bytesToRead > 0) {
2269  char *ptr = d->readBuffer.reserve(bytesToRead);
2270  qint64 readBytes = d->socketEngine->read(ptr, bytesToRead);
2271  if (readBytes == -2) {
2272  // No bytes currently available for reading.
2273  d->readBuffer.chop(bytesToRead);
2274  } else {
2275  d->readBuffer.chop(int(bytesToRead - (readBytes < 0 ? qint64(0) : readBytes)));
2276  }
2277  }
2278  }
2279 
2280  // First try to satisfy the read from the buffer
2281  qint64 bytesToRead = qMin(qint64(d->readBuffer.size()), maxSize);
2282  qint64 readSoFar = 0;
2283  while (readSoFar < bytesToRead) {
2284  const char *ptr = d->readBuffer.readPointer();
2285  int bytesToReadFromThisBlock = qMin(int(bytesToRead - readSoFar),
2286  d->readBuffer.nextDataBlockSize());
2287  memcpy(data + readSoFar, ptr, bytesToReadFromThisBlock);
2288  readSoFar += bytesToReadFromThisBlock;
2289  d->readBuffer.free(bytesToReadFromThisBlock);
2290  }
2291 
2292  if (d->socketEngine && !d->socketEngine->isReadNotificationEnabled() && d->socketEngine->isValid())
2293  d->socketEngine->setReadNotificationEnabled(true);
2294 
2295  if (readSoFar > 0) {
2296  // we read some data from buffer.
2297  // Just return, readyRead will be emitted again
2298 #if defined (QABSTRACTSOCKET_DEBUG)
2299  qDebug("QAbstractSocket::readData(%p '%c (0x%.2x)', %lli) == %lli [buffer]",
2300  data, isprint(int(uchar(*data))) ? *data : '?', *data, maxSize, readSoFar);
2301 #endif
2302 
2303  if (d->readBuffer.isEmpty() && d->socketEngine)
2304  d->socketEngine->setReadNotificationEnabled(true);
2305  return readSoFar;
2306  }
2307 
2308  // This code path is for Unbuffered QTcpSocket or for connected UDP
2309 
2310  if (!d->isBuffered) {
2311  if (!d->socketEngine)
2312  return -1; // no socket engine is probably EOF
2313  if (!d->socketEngine->isValid())
2314  return -1; // This is for unbuffered TCP when we already had been disconnected
2315  if (d->state != QAbstractSocket::ConnectedState)
2316  return -1; // This is for unbuffered TCP if we're not connected yet
2317  qint64 readBytes = d->socketEngine->read(data, maxSize);
2318  if (readBytes == -2) {
2319  // -2 from the engine means no bytes available (EAGAIN) so read more later
2320  return 0;
2321  } else if (readBytes < 0) {
2322  d->socketError = d->socketEngine->error();
2323  setErrorString(d->socketEngine->errorString());
2324  d->resetSocketLayer();
2326  } else if (!d->socketEngine->isReadNotificationEnabled()) {
2327  // Only do this when there was no error
2328  d->socketEngine->setReadNotificationEnabled(true);
2329  }
2330 
2331 #if defined (QABSTRACTSOCKET_DEBUG)
2332  qDebug("QAbstractSocket::readData(%p \"%s\", %lli) == %lld [engine]",
2333  data, qt_prettyDebug(data, 32, readBytes).data(), maxSize,
2334  readBytes);
2335 #endif
2336  return readBytes;
2337  }
2338 
2339 
2340 #if defined (QABSTRACTSOCKET_DEBUG)
2341  qDebug("QAbstractSocket::readData(%p \"%s\", %lli) == %lld [unreachable]",
2342  data, qt_prettyDebug(data, qMin<qint64>(32, readSoFar), readSoFar).data(),
2343  maxSize, readSoFar);
2344 #endif
2345  return readSoFar;
2346 }
double d
Definition: qnumeric_p.h:62
Q_DECL_CONSTEXPR const T & qMin(const T &a, const T &b)
Definition: qglobal.h:1215
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
unsigned char uchar
Definition: qglobal.h:994
static const char * data(const QByteArray &arr)
const T * ptr(const T &t)
__int64 qint64
Definition: qglobal.h:942
void setErrorString(const QString &errorString)
Sets the human readable description of the last device error that occurred to str.
Definition: qiodevice.cpp:1660
The QAbstractSocket class provides the base functionality common to all socket types.

◆ readLineData()

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

Reimplemented Function

Reimplemented from QIODevice.

Definition at line 2350 of file qabstractsocket.cpp.

2351 {
2352  return QIODevice::readLineData(data, maxlen);
2353 }
virtual qint64 readLineData(char *data, qint64 maxlen)
Reads up to maxSize characters into data and returns the number of characters read.
Definition: qiodevice.cpp:1285
static const char * data(const QByteArray &arr)

◆ setLocalAddress()

void QAbstractSocket::setLocalAddress ( const QHostAddress address)
protected

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

Since
4.1

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., QUdpSocket::bind()).

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

Definition at line 2469 of file qabstractsocket.cpp.

2470 {
2472  d->localAddress = address;
2473 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QAbstractSocket class provides the base functionality common to all socket types.

◆ setLocalPort()

void QAbstractSocket::setLocalPort ( quint16  port)
protected

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

Since
4.1

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., QUdpSocket::bind()).

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

Definition at line 2444 of file qabstractsocket.cpp.

2445 {
2447  d->localPort = port;
2448 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QAbstractSocket class provides the base functionality common to all socket types.

◆ setPeerAddress()

void QAbstractSocket::setPeerAddress ( const QHostAddress address)
protected

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

Since
4.1

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 2513 of file qabstractsocket.cpp.

2514 {
2516  d->peerAddress = address;
2517 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QAbstractSocket class provides the base functionality common to all socket types.

◆ setPeerName()

void QAbstractSocket::setPeerName ( const QString name)
protected

Sets the host name of the remote peer to name.

Since
4.1

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 2534 of file qabstractsocket.cpp.

2535 {
2537  d->peerName = name;
2538 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
const char * name
The QAbstractSocket class provides the base functionality common to all socket types.

◆ setPeerPort()

void QAbstractSocket::setPeerPort ( quint16  port)
protected

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

Since
4.1

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 2491 of file qabstractsocket.cpp.

2492 {
2494  d->peerPort = port;
2495 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QAbstractSocket class provides the base functionality common to all socket types.

◆ setProxy()

void QAbstractSocket::setProxy ( const QNetworkProxy networkProxy)

Sets the explicit network proxy for this socket to networkProxy.

Since
4.1

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

socket->setProxy(QNetworkProxy::NoProxy);

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 2841 of file qabstractsocket.cpp.

Referenced by QHttpPrivate::_q_slotSendRequest(), QSocks5SocketEngine::bind(), QHttpNetworkConnectionChannel::init(), and QSocks5SocketEnginePrivate::initialize().

2842 {
2844  d->proxy = networkProxy;
2845 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QAbstractSocket class provides the base functionality common to all socket types.

◆ setReadBufferSize()

void QAbstractSocket::setReadBufferSize ( qint64  size)

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

Definition at line 2743 of file qabstractsocket.cpp.

Referenced by QHttpNetworkConnectionChannel::ensureConnection(), and QSslSocketBackendPrivate::startHandshake().

2744 {
2746 
2747 #ifndef QT_NO_OPENSSL
2748  // Manual polymorphism; setReadBufferSize() isn't virtual, but QSslSocket overloads
2749  // it.
2750  if (QSslSocket *socket = qobject_cast<QSslSocket *>(this)) {
2751  socket->setReadBufferSize(size);
2752  return;
2753  }
2754 #endif
2755 
2756  if (d->readBufferMaxSize == size)
2757  return;
2758  d->readBufferMaxSize = size;
2759  if (!d->readSocketNotifierCalled && d->socketEngine) {
2760  // ensure that the read notification is enabled if we've now got
2761  // room in the read buffer
2762  // but only if we're not inside canReadNotification -- that will take care on its own
2763  if ((size == 0 || d->readBuffer.size() < size) && d->state == QAbstractSocket::ConnectedState) // Do not change the notifier unless we are connected.
2764  d->socketEngine->setReadNotificationEnabled(true);
2765  }
2766 }
double d
Definition: qnumeric_p.h:62
virtual qint64 size() const
For open random-access devices, this function returns the size of the device.
Definition: qiodevice.cpp:642
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
The QAbstractSocket class provides the base functionality common to all socket types.

◆ setSocketDescriptor()

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

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.

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

See also
socketDescriptor()

Definition at line 1684 of file qabstractsocket.cpp.

Referenced by QTcpServer::incomingConnection().

1686 {
1688 #ifndef QT_NO_OPENSSL
1689  if (QSslSocket *socket = qobject_cast<QSslSocket *>(this))
1690  return socket->setSocketDescriptor(socketDescriptor, socketState, openMode);
1691 #endif
1692 
1693  d->resetSocketLayer();
1695  if (!d->socketEngine) {
1696  d->socketError = UnsupportedSocketOperationError;
1697  setErrorString(tr("Operation on socket is not supported"));
1698  return false;
1699  }
1700 #ifndef QT_NO_BEARERMANAGEMENT
1701  //copy network session down to the socket engine (if it has been set)
1702  d->socketEngine->setProperty("_q_networksession", property("_q_networksession"));
1703 #endif
1704  bool result = d->socketEngine->initialize(socketDescriptor, socketState);
1705  if (!result) {
1706  d->socketError = d->socketEngine->error();
1707  setErrorString(d->socketEngine->errorString());
1708  return false;
1709  }
1710 
1711  if (d->threadData->eventDispatcher)
1712  d->socketEngine->setReceiver(d);
1713 
1715 
1716  if (d->state != socketState) {
1717  d->state = socketState;
1718  emit stateChanged(d->state);
1719  }
1720 
1721  d->pendingClose = false;
1722  d->socketEngine->setReadNotificationEnabled(true);
1723  d->localPort = d->socketEngine->localPort();
1724  d->peerPort = d->socketEngine->peerPort();
1725  d->localAddress = d->socketEngine->localAddress();
1726  d->peerAddress = d->socketEngine->peerAddress();
1727  d->cachedSocketDescriptor = socketDescriptor;
1728 
1729  return true;
1730 }
double d
Definition: qnumeric_p.h:62
int socketDescriptor() const
Returns the native socket descriptor of the QAbstractSocket object if this is available; otherwise re...
static QAbstractSocketEngine * createSocketEngine(QAbstractSocket::SocketType socketType, const QNetworkProxy &, QObject *parent)
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
static QString tr(const char *sourceText, const char *comment=0, int n=-1)
#define Q_D(Class)
Definition: qglobal.h:2482
#define emit
Definition: qobjectdefs.h:76
OpenMode openMode() const
Returns the mode in which the device has been opened; i.e.
Definition: qiodevice.cpp:465
void setErrorString(const QString &errorString)
Sets the human readable description of the last device error that occurred to str.
Definition: qiodevice.cpp:1660
virtual bool open(OpenMode mode)
Opens the device and sets its OpenMode to mode.
Definition: qiodevice.cpp:570
QVariant property(const char *name) const
Returns the value of the object&#39;s name property.
Definition: qobject.cpp:3807
void stateChanged(QAbstractSocket::SocketState)
This signal is emitted whenever QAbstractSocket&#39;s state changes.
The QAbstractSocket class provides the base functionality common to all socket types.

◆ setSocketError()

void QAbstractSocket::setSocketError ( SocketError  socketError)
protected

Sets the type of error that last occurred to socketError.

See also
setSocketState(), setErrorString()

Definition at line 2813 of file qabstractsocket.cpp.

2814 {
2815  d_func()->socketError = socketError;
2816 }

◆ setSocketOption()

void QAbstractSocket::setSocketOption ( QAbstractSocket::SocketOption  option,
const QVariant value 
)

Sets the given option to the value described by value.

Since
4.6
See also
socketOption()

Definition at line 1741 of file qabstractsocket.cpp.

Referenced by QHttpNetworkConnectionChannel::_q_connected(), and QFtpPI::connected().

1742 {
1743 #ifndef QT_NO_OPENSSL
1744  if (QSslSocket *sslSocket = qobject_cast<QSslSocket*>(this)) {
1745  sslSocket->setSocketOption(option, value);
1746  return;
1747  }
1748 #endif
1749 
1750  if (!d_func()->socketEngine)
1751  return;
1752 
1753  switch (option) {
1754  case LowDelayOption:
1755  d_func()->socketEngine->setOption(QAbstractSocketEngine::LowDelayOption, value.toInt());
1756  break;
1757 
1758  case KeepAliveOption:
1759  d_func()->socketEngine->setOption(QAbstractSocketEngine::KeepAliveOption, value.toInt());
1760  break;
1761 
1762  case MulticastTtlOption:
1763  d_func()->socketEngine->setOption(QAbstractSocketEngine::MulticastTtlOption, value.toInt());
1764  break;
1765 
1767  d_func()->socketEngine->setOption(QAbstractSocketEngine::MulticastLoopbackOption, value.toInt());
1768  break;
1769  }
1770 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
int toInt(bool *ok=0) const
Returns the variant as an int if the variant has type() Int , Bool , ByteArray , Char ...
Definition: qvariant.cpp:2625

◆ setSocketState()

void QAbstractSocket::setSocketState ( SocketState  state)
protected

Sets the state of the socket to state.

See also
state()

Definition at line 2783 of file qabstractsocket.cpp.

2784 {
2785  d_func()->state = state;
2786 }
SocketState state() const
Returns the state of the socket.

◆ socketDescriptor()

int QAbstractSocket::socketDescriptor ( ) const

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 1666 of file qabstractsocket.cpp.

Referenced by QSslSocketPrivate::_q_connectedSlot(), QLocalServerPrivate::_q_onNewConnection(), QLocalSocket::setSocketDescriptor(), and setSocketDescriptor().

1667 {
1668  Q_D(const QAbstractSocket);
1669  return d->cachedSocketDescriptor;
1670 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QAbstractSocket class provides the base functionality common to all socket types.

◆ socketOption()

QVariant QAbstractSocket::socketOption ( QAbstractSocket::SocketOption  option)

Returns the value of the option option.

Since
4.6
See also
setSocketOption()

Definition at line 1781 of file qabstractsocket.cpp.

1782 {
1783 #ifndef QT_NO_OPENSSL
1784  if (QSslSocket *sslSocket = qobject_cast<QSslSocket*>(this)) {
1785  return sslSocket->socketOption(option);
1786  }
1787 #endif
1788 
1789  if (!d_func()->socketEngine)
1790  return QVariant();
1791 
1792  int ret = -1;
1793  switch (option) {
1794  case LowDelayOption:
1795  ret = d_func()->socketEngine->option(QAbstractSocketEngine::LowDelayOption);
1796  break;
1797 
1798  case KeepAliveOption:
1799  ret = d_func()->socketEngine->option(QAbstractSocketEngine::KeepAliveOption);
1800  break;
1801 
1802  case MulticastTtlOption:
1803  ret = d_func()->socketEngine->option(QAbstractSocketEngine::MulticastTtlOption);
1804  break;
1806  ret = d_func()->socketEngine->option(QAbstractSocketEngine::MulticastLoopbackOption);
1807  break;
1808  }
1809  if (ret == -1)
1810  return QVariant();
1811  else
1812  return QVariant(ret);
1813 }
The QVariant class acts like a union for the most common Qt data types.
Definition: qvariant.h:92
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67

◆ socketType()

QAbstractSocket::SocketType QAbstractSocket::socketType ( ) const

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

See also
QTcpSocket, QUdpSocket

Definition at line 2793 of file qabstractsocket.cpp.

Referenced by QAbstractSocket().

2794 {
2795  return d_func()->socketType;
2796 }

◆ state()

QAbstractSocket::SocketState QAbstractSocket::state ( ) const

◆ 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_REGISTER_METATYPE() and qRegisterMetaType().

See also
state(), {Creating Custom Qt Types}

Referenced by QUdpSocket::bind(), connectToHostImplementation(), disconnectFromHostImplementation(), setSocketDescriptor(), and waitForConnected().

◆ waitForBytesWritten()

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

Reimplemented Function

Reimplemented from QIODevice.

Reimplemented in QSslSocket.

Definition at line 2006 of file qabstractsocket.cpp.

2007 {
2009 #if defined (QABSTRACTSOCKET_DEBUG)
2010  qDebug("QAbstractSocket::waitForBytesWritten(%i)", msecs);
2011 #endif
2012 
2013  // require calling connectToHost() before waitForBytesWritten()
2014  if (state() == UnconnectedState) {
2015  qWarning("QAbstractSocket::waitForBytesWritten() is not allowed in UnconnectedState");
2016  return false;
2017  }
2018 
2019  if (d->writeBuffer.isEmpty())
2020  return false;
2021 
2022  QElapsedTimer stopWatch;
2023  stopWatch.start();
2024 
2025  // handle a socket in connecting state
2026  if (state() == HostLookupState || state() == ConnectingState) {
2027  if (!waitForConnected(msecs))
2028  return false;
2029  }
2030 
2031  forever {
2032  bool readyToRead = false;
2033  bool readyToWrite = false;
2034  if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, true, !d->writeBuffer.isEmpty(),
2035  qt_timeout_value(msecs, stopWatch.elapsed()))) {
2036  d->socketError = d->socketEngine->error();
2037  setErrorString(d->socketEngine->errorString());
2038 #if defined (QABSTRACTSOCKET_DEBUG)
2039  qDebug("QAbstractSocket::waitForBytesWritten(%i) failed (%i, %s)",
2040  msecs, d->socketError, errorString().toLatin1().constData());
2041 #endif
2042  emit error(d->socketError);
2043  if (d->socketError != SocketTimeoutError)
2044  close();
2045  return false;
2046  }
2047 
2048  if (readyToRead) {
2049 #if defined (QABSTRACTSOCKET_DEBUG)
2050  qDebug("QAbstractSocket::waitForBytesWritten calls canReadNotification");
2051 #endif
2052  if(!d->canReadNotification())
2053  return false;
2054  }
2055 
2056 
2057  if (readyToWrite) {
2058  if (d->canWriteNotification()) {
2059 #if defined (QABSTRACTSOCKET_DEBUG)
2060  qDebug("QAbstractSocket::waitForBytesWritten returns true");
2061 #endif
2062  return true;
2063  }
2064  }
2065 
2066  if (state() != ConnectedState)
2067  return false;
2068  }
2069  return false;
2070 }
double d
Definition: qnumeric_p.h:62
QString errorString() const
Returns a human-readable description of the last device error that occurred.
Definition: qiodevice.cpp:1671
#define Q_D(Class)
Definition: qglobal.h:2482
The QElapsedTimer class provides a fast way to calculate elapsed times.
Definition: qelapsedtimer.h:53
qint64 elapsed() const
Returns the number of milliseconds since this QElapsedTimer was last started.
Q_CORE_EXPORT void qDebug(const char *,...)
#define emit
Definition: qobjectdefs.h:76
bool waitForConnected(int msecs=30000)
Waits until the socket is connected, up to msecs milliseconds.
Q_CORE_EXPORT void qWarning(const char *,...)
void close()
Closes the I/O device for the socket, disconnects the socket&#39;s connection with the host...
void setErrorString(const QString &errorString)
Sets the human readable description of the last device error that occurred to str.
Definition: qiodevice.cpp:1660
static int qt_timeout_value(int msecs, int elapsed)
SocketError error() const
Returns the type of error that last occurred.
The QAbstractSocket class provides the base functionality common to all socket types.
void start()
Starts this timer.
SocketState state() const
Returns the state of the socket.
#define forever
This macro is provided for convenience for writing infinite loops.
Definition: qglobal.h:2452

◆ waitForConnected()

bool QAbstractSocket::waitForConnected ( int  msecs = 30000)

Waits until the socket is connected, up to msecs milliseconds.

If the connection has been established, this function returns true; otherwise it returns false. In the case where it returns false, you can call error() to determine the cause of the error.

The following example waits up to one second for a connection to be established:

socket->connectToHost("imap", 143);
if (socket->waitForConnected(1000))
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.
See also
connectToHost(), connected()

Definition at line 1851 of file qabstractsocket.cpp.

Referenced by waitForBytesWritten(), waitForDisconnected(), and waitForReadyRead().

1852 {
1854 #if defined (QABSTRACTSOCKET_DEBUG)
1855  qDebug("QAbstractSocket::waitForConnected(%i)", msecs);
1856 #endif
1857 
1858  if (state() == ConnectedState) {
1859 #if defined (QABSTRACTSOCKET_DEBUG)
1860  qDebug("QAbstractSocket::waitForConnected(%i) already connected", msecs);
1861 #endif
1862  return true;
1863  }
1864 
1865 #ifndef QT_NO_OPENSSL
1866  // Manual polymorphism; this function is not virtual, but has an overload
1867  // in QSslSocket.
1868  if (QSslSocket *socket = qobject_cast<QSslSocket *>(this))
1869  return socket->waitForConnected(msecs);
1870 #endif
1871 
1872  bool wasPendingClose = d->pendingClose;
1873  d->pendingClose = false;
1874  QElapsedTimer stopWatch;
1875  stopWatch.start();
1876 
1877  if (d->state == HostLookupState) {
1878 #if defined (QABSTRACTSOCKET_DEBUG)
1879  qDebug("QAbstractSocket::waitForConnected(%i) doing host name lookup", msecs);
1880 #endif
1881  QHostInfo::abortHostLookup(d->hostLookupId);
1882  d->hostLookupId = -1;
1883 #ifndef QT_NO_BEARERMANAGEMENT
1884  QSharedPointer<QNetworkSession> networkSession;
1885  QVariant v(property("_q_networksession"));
1886  if (v.isValid()) {
1887  networkSession = qvariant_cast< QSharedPointer<QNetworkSession> >(v);
1888  d->_q_startConnecting(QHostInfoPrivate::fromName(d->hostName, networkSession));
1889  } else
1890 #endif
1891  d->_q_startConnecting(QHostInfo::fromName(d->hostName));
1892  }
1893  if (state() == UnconnectedState)
1894  return false; // connect not im progress anymore!
1895 
1896  bool timedOut = true;
1897 #if defined (QABSTRACTSOCKET_DEBUG)
1898  int attempt = 1;
1899 #endif
1900  while (state() == ConnectingState && (msecs == -1 || stopWatch.elapsed() < msecs)) {
1901  int timeout = qt_timeout_value(msecs, stopWatch.elapsed());
1902  if (msecs != -1 && timeout > QT_CONNECT_TIMEOUT)
1903  timeout = QT_CONNECT_TIMEOUT;
1904 #if defined (QABSTRACTSOCKET_DEBUG)
1905  qDebug("QAbstractSocket::waitForConnected(%i) waiting %.2f secs for connection attempt #%i",
1906  msecs, timeout / 1000.0, attempt++);
1907 #endif
1908  timedOut = false;
1909 
1910  if (d->socketEngine && d->socketEngine->waitForWrite(timeout, &timedOut) && !timedOut) {
1911  d->_q_testConnection();
1912  } else {
1913  d->_q_connectToNextAddress();
1914  }
1915  }
1916 
1917  if ((timedOut && state() != ConnectedState) || state() == ConnectingState) {
1918  d->socketError = SocketTimeoutError;
1919  d->state = UnconnectedState;
1920  emit stateChanged(d->state);
1921  d->resetSocketLayer();
1922  setErrorString(tr("Socket operation timed out"));
1923  }
1924 
1925 #if defined (QABSTRACTSOCKET_DEBUG)
1926  qDebug("QAbstractSocket::waitForConnected(%i) == %s", msecs,
1927  state() == ConnectedState ? "true" : "false");
1928 #endif
1929  if (state() != ConnectedState)
1930  return false;
1931  if (wasPendingClose)
1933  return true;
1934 }
The QVariant class acts like a union for the most common Qt data types.
Definition: qvariant.h:92
double d
Definition: qnumeric_p.h:62
static void abortHostLookup(int lookupId)
Aborts the host lookup with the ID id, as returned by lookupHost().
Definition: qhostinfo.cpp:255
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
static QString tr(const char *sourceText, const char *comment=0, int n=-1)
#define Q_D(Class)
Definition: qglobal.h:2482
The QElapsedTimer class provides a fast way to calculate elapsed times.
Definition: qelapsedtimer.h:53
qint64 elapsed() const
Returns the number of milliseconds since this QElapsedTimer was last started.
Q_CORE_EXPORT void qDebug(const char *,...)
#define emit
Definition: qobjectdefs.h:76
static QHostInfo fromName(const QString &hostName, QSharedPointer< QNetworkSession > networkSession)
Definition: qhostinfo.cpp:286
#define QT_CONNECT_TIMEOUT
static QHostInfo fromName(const QString &name)
Looks up the IP address(es) for the given host name.
Definition: qhostinfo.cpp:273
void setErrorString(const QString &errorString)
Sets the human readable description of the last device error that occurred to str.
Definition: qiodevice.cpp:1660
T qvariant_cast(const QVariant &)
Definition: qvariant.h:571
QVariant property(const char *name) const
Returns the value of the object&#39;s name property.
Definition: qobject.cpp:3807
void disconnectFromHost()
Attempts to close the socket.
static int qt_timeout_value(int msecs, int elapsed)
void stateChanged(QAbstractSocket::SocketState)
This signal is emitted whenever QAbstractSocket&#39;s state changes.
The QAbstractSocket class provides the base functionality common to all socket types.
void start()
Starts this timer.
SocketState state() const
Returns the state of the socket.

◆ waitForDisconnected()

bool QAbstractSocket::waitForDisconnected ( int  msecs = 30000)

Waits until the socket has disconnected, up to msecs milliseconds.

If the connection has been disconnected, 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 closed:

socket->disconnectFromHost();
if (socket->state() == QAbstractSocket::UnconnectedState ||
socket->waitForDisconnected(1000))
qDebug("Disconnected!");

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

See also
disconnectFromHost(), close()

Definition at line 2088 of file qabstractsocket.cpp.

2089 {
2091 #ifndef QT_NO_OPENSSL
2092  // Manual polymorphism; this function is not virtual, but has an overload
2093  // in QSslSocket.
2094  if (QSslSocket *socket = qobject_cast<QSslSocket *>(this))
2095  return socket->waitForDisconnected(msecs);
2096 #endif
2097 
2098  // require calling connectToHost() before waitForDisconnected()
2099  if (state() == UnconnectedState) {
2100  qWarning("QAbstractSocket::waitForDisconnected() is not allowed in UnconnectedState");
2101  return false;
2102  }
2103 
2104  QElapsedTimer stopWatch;
2105  stopWatch.start();
2106 
2107  // handle a socket in connecting state
2108  if (state() == HostLookupState || state() == ConnectingState) {
2109  if (!waitForConnected(msecs))
2110  return false;
2111  if (state() == UnconnectedState)
2112  return true;
2113  }
2114 
2115  forever {
2116  bool readyToRead = false;
2117  bool readyToWrite = false;
2118  if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, state() == ConnectedState,
2119  !d->writeBuffer.isEmpty(),
2120  qt_timeout_value(msecs, stopWatch.elapsed()))) {
2121  d->socketError = d->socketEngine->error();
2122  setErrorString(d->socketEngine->errorString());
2123 #if defined (QABSTRACTSOCKET_DEBUG)
2124  qDebug("QAbstractSocket::waitForReadyRead(%i) failed (%i, %s)",
2125  msecs, d->socketError, errorString().toLatin1().constData());
2126 #endif
2127  emit error(d->socketError);
2128  if (d->socketError != SocketTimeoutError)
2129  close();
2130  return false;
2131  }
2132 
2133  if (readyToRead)
2134  d->canReadNotification();
2135  if (readyToWrite)
2136  d->canWriteNotification();
2137 
2138  if (state() == UnconnectedState)
2139  return true;
2140  }
2141  return false;
2142 }
double d
Definition: qnumeric_p.h:62
QString errorString() const
Returns a human-readable description of the last device error that occurred.
Definition: qiodevice.cpp:1671
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
The QElapsedTimer class provides a fast way to calculate elapsed times.
Definition: qelapsedtimer.h:53
qint64 elapsed() const
Returns the number of milliseconds since this QElapsedTimer was last started.
Q_CORE_EXPORT void qDebug(const char *,...)
#define emit
Definition: qobjectdefs.h:76
bool waitForConnected(int msecs=30000)
Waits until the socket is connected, up to msecs milliseconds.
Q_CORE_EXPORT void qWarning(const char *,...)
void close()
Closes the I/O device for the socket, disconnects the socket&#39;s connection with the host...
void setErrorString(const QString &errorString)
Sets the human readable description of the last device error that occurred to str.
Definition: qiodevice.cpp:1660
static int qt_timeout_value(int msecs, int elapsed)
SocketError error() const
Returns the type of error that last occurred.
The QAbstractSocket class provides the base functionality common to all socket types.
void start()
Starts this timer.
SocketState state() const
Returns the state of the socket.
#define forever
This macro is provided for convenience for writing infinite loops.
Definition: qglobal.h:2452

◆ waitForReadyRead()

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

This function blocks until new data is available for reading and the 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).

See also
waitForBytesWritten()

Reimplemented from QIODevice.

Reimplemented in QSslSocket.

Definition at line 1948 of file qabstractsocket.cpp.

Referenced by QSocks5SocketEngine::bind().

1949 {
1951 #if defined (QABSTRACTSOCKET_DEBUG)
1952  qDebug("QAbstractSocket::waitForReadyRead(%i)", msecs);
1953 #endif
1954 
1955  // require calling connectToHost() before waitForReadyRead()
1956  if (state() == UnconnectedState) {
1957  /* If all you have is a QIODevice pointer to an abstractsocket, you cannot check
1958  this, so you cannot avoid this warning. */
1959 // qWarning("QAbstractSocket::waitForReadyRead() is not allowed in UnconnectedState");
1960  return false;
1961  }
1962 
1963  QElapsedTimer stopWatch;
1964  stopWatch.start();
1965 
1966  // handle a socket in connecting state
1967  if (state() == HostLookupState || state() == ConnectingState) {
1968  if (!waitForConnected(msecs))
1969  return false;
1970  }
1971 
1972  Q_ASSERT(d->socketEngine);
1973  do {
1974  bool readyToRead = false;
1975  bool readyToWrite = false;
1976  if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, true, !d->writeBuffer.isEmpty(),
1977  qt_timeout_value(msecs, stopWatch.elapsed()))) {
1978  d->socketError = d->socketEngine->error();
1979  setErrorString(d->socketEngine->errorString());
1980 #if defined (QABSTRACTSOCKET_DEBUG)
1981  qDebug("QAbstractSocket::waitForReadyRead(%i) failed (%i, %s)",
1982  msecs, d->socketError, errorString().toLatin1().constData());
1983 #endif
1984  emit error(d->socketError);
1985  if (d->socketError != SocketTimeoutError)
1986  close();
1987  return false;
1988  }
1989 
1990  if (readyToRead) {
1991  if (d->canReadNotification())
1992  return true;
1993  }
1994 
1995  if (readyToWrite)
1996  d->canWriteNotification();
1997 
1998  if (state() != ConnectedState)
1999  return false;
2000  } while (msecs == -1 || qt_timeout_value(msecs, stopWatch.elapsed()) > 0);
2001  return false;
2002 }
double d
Definition: qnumeric_p.h:62
QString errorString() const
Returns a human-readable description of the last device error that occurred.
Definition: qiodevice.cpp:1671
#define Q_ASSERT(cond)
Definition: qglobal.h:1823
#define Q_D(Class)
Definition: qglobal.h:2482
The QElapsedTimer class provides a fast way to calculate elapsed times.
Definition: qelapsedtimer.h:53
qint64 elapsed() const
Returns the number of milliseconds since this QElapsedTimer was last started.
Q_CORE_EXPORT void qDebug(const char *,...)
#define emit
Definition: qobjectdefs.h:76
bool waitForConnected(int msecs=30000)
Waits until the socket is connected, up to msecs milliseconds.
void close()
Closes the I/O device for the socket, disconnects the socket&#39;s connection with the host...
void setErrorString(const QString &errorString)
Sets the human readable description of the last device error that occurred to str.
Definition: qiodevice.cpp:1660
static int qt_timeout_value(int msecs, int elapsed)
SocketError error() const
Returns the type of error that last occurred.
The QAbstractSocket class provides the base functionality common to all socket types.
void start()
Starts this timer.
SocketState state() const
Returns the state of the socket.

◆ writeData()

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

Reimplemented Function

Implements QIODevice.

Reimplemented in QSslSocket.

Definition at line 2357 of file qabstractsocket.cpp.

2358 {
2360  if (d->state == QAbstractSocket::UnconnectedState) {
2361  d->socketError = QAbstractSocket::UnknownSocketError;
2362  setErrorString(tr("Socket is not connected"));
2363  return -1;
2364  }
2365 
2366  if (!d->isBuffered && d->socketType == TcpSocket && d->writeBuffer.isEmpty()) {
2367  // This code is for the new Unbuffered QTcpSocket use case
2368  qint64 written = d->socketEngine->write(data, size);
2369  if (written < 0) {
2370  d->socketError = d->socketEngine->error();
2371  setErrorString(d->socketEngine->errorString());
2372  return written;
2373  } else if (written < size) {
2374  // Buffer what was not written yet
2375  char *ptr = d->writeBuffer.reserve(size - written);
2376  memcpy(ptr, data + written, size - written);
2377  if (d->socketEngine)
2378  d->socketEngine->setWriteNotificationEnabled(true);
2379  }
2380  return size; // size=actually written + what has been buffered
2381  } else if (!d->isBuffered && d->socketType != TcpSocket) {
2382  // This is for a QUdpSocket that was connect()ed
2383  qint64 written = d->socketEngine->write(data, size);
2384  if (written < 0) {
2385  d->socketError = d->socketEngine->error();
2386  setErrorString(d->socketEngine->errorString());
2387  } else if (!d->writeBuffer.isEmpty()) {
2388  d->socketEngine->setWriteNotificationEnabled(true);
2389  }
2390 
2391 #if defined (QABSTRACTSOCKET_DEBUG)
2392  qDebug("QAbstractSocket::writeData(%p \"%s\", %lli) == %lli", data,
2393  qt_prettyDebug(data, qMin((int)size, 32), size).data(),
2394  size, written);
2395 #endif
2396  if (written >= 0)
2397  emit bytesWritten(written);
2398  return written;
2399  }
2400 
2401  // This is the code path for normal buffered QTcpSocket or
2402  // unbuffered QTcpSocket when there was already something in the
2403  // write buffer and therefore we could not do a direct engine write.
2404  // We just write to our write buffer and enable the write notifier
2405  // The write notifier then flush()es the buffer.
2406 
2407  char *ptr = d->writeBuffer.reserve(size);
2408  if (size == 1)
2409  *ptr = *data;
2410  else
2411  memcpy(ptr, data, size);
2412 
2413  qint64 written = size;
2414 
2415  if (d->socketEngine && !d->writeBuffer.isEmpty())
2416  d->socketEngine->setWriteNotificationEnabled(true);
2417 
2418 #if defined (QABSTRACTSOCKET_DEBUG)
2419  qDebug("QAbstractSocket::writeData(%p \"%s\", %lli) == %lli", data,
2420  qt_prettyDebug(data, qMin((int)size, 32), size).data(),
2421  size, written);
2422 #endif
2423  return written;
2424 }
double d
Definition: qnumeric_p.h:62
virtual qint64 size() const
For open random-access devices, this function returns the size of the device.
Definition: qiodevice.cpp:642
Q_DECL_CONSTEXPR const T & qMin(const T &a, const T &b)
Definition: qglobal.h:1215
static QString tr(const char *sourceText, const char *comment=0, int n=-1)
void bytesWritten(qint64 bytes)
This signal is emitted every time a payload of data has been written to the device.
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
#define emit
Definition: qobjectdefs.h:76
static const char * data(const QByteArray &arr)
const T * ptr(const T &t)
__int64 qint64
Definition: qglobal.h:942
void setErrorString(const QString &errorString)
Sets the human readable description of the last device error that occurred to str.
Definition: qiodevice.cpp:1660
The QAbstractSocket class provides the base functionality common to all socket types.

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