Qabstractsocket error occurred

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

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

#include <qabstractsocket.h>

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 QObjectList &  children () 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< QByteArray >  dynamicPropertyNames () 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 QMetaObject *  metaObject () 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
 
QObject *  parent () 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…
 
QThread *  thread () const
  Returns the thread in which the object lives. More…
 
QObjectUserData *  userData (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…
 
QObject *  sender () const
  Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns 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< QObjectData >  d_ptr
 
- Static Protected Variables inherited from QObject
static const QMetaObject  staticQtMetaObject
 
- Related Functions inherited from QObject
qFindChildqFindChildren (const QObject *obj, const QString &name)()
 
QList< T >  qFindChildrenqFindChildren (const QObject *obj, const QString &name)()
 
QList< T >  qFindChildrenqFindChildren (const QObject *obj, const QRegExp &regExp)()
 
T *  qobject_cast (QObject *object)
 
  QObjectList
 
void *  qt_find_obj_child (QObject *parent, const char *type, const QString &name)
  Returns a pointer to the object named name that inherits type and with a given parent. More…
 

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:

  • Instantiate QTcpSocket or QUdpSocket.
  • Create a native socket descriptor, instantiate QAbstractSocket, and call setSocketDescriptor() to wrap the native socket.

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:

  • waitForConnected() blocks until a connection has been established.

  • waitForReadyRead() blocks until new data is available for reading.

  • waitForBytesWritten() blocks until one payload of data has been written to the socket.

  • waitForDisconnected() blocks until the connection has closed.

We show an example:

int numRead = 0, numReadTotal = 0;

char buffer[50];

numRead = socket.read(buffer, 50);

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.

◆ 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.)
  • UnknownSocketError An unidentified error occurred.
    See also
    QAbstractSocket::error()
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.

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

102  {

110 #ifdef QT3_SUPPORT

111  ,

117  Connection = ConnectedState

118 #endif

119  };

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

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.

1353 {

1355 #if defined(QABSTRACTSOCKET_DEBUG)

1356  qDebug(«QAbstractSocket::QAbstractSocket(%p)», parent);

1357 #endif

1359 }

SocketType socketType() const

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

Q_CORE_EXPORT void qDebug(const char *,…)

QIODevice()

Constructs a QIODevice object.

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

1372 }

void abort()

Aborts the current connection and resets the socket.

Q_CORE_EXPORT void qDebug(const char *,…)

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

◆ QAbstractSocket() [2/2]

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.

1335 {

1337 #if defined(QABSTRACTSOCKET_DEBUG)

1338  qDebug(«QAbstractSocket::QAbstractSocket(%sSocket, QAbstractSocketPrivate == %p, parent == %p)»,

1340  ? «Udp» : «Unknown», &dd, parent);

1341 #endif

1343 }

SocketType socketType() const

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

Q_CORE_EXPORT void qDebug(const char *,…)

QIODevice()

Constructs a QIODevice object.

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

◆ 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

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;

2174 }

The QSslSocket class provides an SSL encrypted socket for both clients and servers.

Q_CORE_EXPORT void qDebug(const char *,…)

void close()

Closes the I/O device for the socket, disconnects the socket'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 {

2201 }

virtual bool atEnd() const

Returns true if the current read and write position is at the end of the device (i.e.

bool isOpen() const

Returns true if the device is open; otherwise returns false.

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

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 }

Q_CORE_EXPORT void qDebug(const char *,…)

virtual qint64 bytesAvailable() const

Returns the number of bytes that are available for reading.

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

◆ bytesToWrite()

qint64 QAbstractSocket::bytesToWrite ( ) const
virtual

◆ 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

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…

◆ 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

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 }

virtual void close()

First emits aboutToClose(), then closes the device and sets its OpenMode to NotOpen.

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

◆ connectToHost() [1/2]

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 {

1417 }

#define Q_ARG(type, data)

The QString class provides a Unicode character string.

OpenMode openMode() const

Returns the mode in which the device has been opened; i.e.

◆ connectToHost() [2/2]

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)…»,

1533 #endif

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.

const char * constData() const

Returns a pointer to the data stored in the byte array.

OpenMode openMode() const

Returns the mode in which the device has been opened; i.e.

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

1437 #endif

1438 

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;

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

1460  d->hostLookupId = -1;

1461  }

1462 

1463 #ifndef QT_NO_NETWORKPROXY

1464 

1465  d->resolveProxy(hostName, port);

1467 

1471  return;

1472  }

1473 #endif

1474 

1476  d->isBuffered = false;

1477  else if (!d_func()->isBuffered)

1479 

1483 

1488  d->_q_startConnecting(info);

1489 #ifndef QT_NO_NETWORKPROXY

1491 

1492  d->startConnectingByName(hostName);

1493  return;

1494 #endif

1495  } else {

1496  if (d->threadData->eventDispatcher) {

1497 

1498 

1499  bool immediateResultValid = false;

1501  this,

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,

1516  ? » (connection in progress)» : «»);

1517 #endif

1518 }

static mach_timebase_info_data_t info

static void abortHostLookup(int lookupId)

Aborts the host lookup with the ID id, as returned by lookupHost().

static QString tr(const char *sourceText, const char *comment=0, int n=-1)

Q_CORE_EXPORT void qDebug(const char *,…)

void setAddresses(const QList< QHostAddress > &addresses)

Sets the list of addresses in this QHostInfo to addresses.

Q_CORE_EXPORT void qWarning(const char *,…)

The QHostInfo class provides static functions for host name lookups.

QByteArray toLatin1() const Q_REQUIRED_RESULT

Returns a Latin-1 representation of the string as a QByteArray.

const char * constData() const

Returns a pointer to the data stored in the byte array.

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.

void setErrorString(const QString &errorString)

Sets the human readable description of the last device error that occurred to str.

virtual bool open(OpenMode mode)

Opens the device and sets its OpenMode to mode.

void stateChanged(QAbstractSocket::SocketState)

This signal is emitted whenever QAbstractSocket's state changes.

The QHostAddress class provides an IP address.

SocketError error() const

Returns the type of error that last occurred.

#define qPrintable(string)

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)

◆ disconnected

void QAbstractSocket::disconnected ( )
signal

◆ disconnectFromHost()

void QAbstractSocket::disconnectFromHost ( )

◆ 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 

2600 #if defined(QABSTRACTSOCKET_DEBUG)

2601  qDebug(«QAbstractSocket::disconnectFromHost() was called on an unconnected socket»);

2602 #endif

2603  return;

2604  }

2605 

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

2616 #endif

2617 

2618 

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

2628  d->hostLookupId = -1;

2629  }

2630  } else {

2631 

2634 #if defined(QABSTRACTSOCKET_DEBUG)

2635  qDebug(«QAbstractSocket::disconnectFromHost() emits stateChanged()(ClosingState)»);

2636 #endif

2638  } else {

2639 #if defined(QABSTRACTSOCKET_DEBUG)

2640  qDebug(«QAbstractSocket::disconnectFromHost() return from delayed close»);

2641 #endif

2642  }

2643 

2644 

2645  if (d->socketEngine && d->socketEngine->isValid() && (d->writeBuffer.size() > 0

2646  || d->socketEngine->bytesToWrite() > 0)) {

2647 

2648 

2649 

2650 

2651 

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,

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 

2675  d->resetSocketLayer();

2679 

2680 #ifdef QT3_SUPPORT

2681  emit delayedCloseFinished();

2682 #endif

2683 

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

2703  }

2704 }

virtual void close()

First emits aboutToClose(), then closes the device and sets its OpenMode to NotOpen.

void readChannelFinished()

This signal is emitted when the input (reading) stream is closed in this device.

static void abortHostLookup(int lookupId)

Aborts the host lookup with the ID id, as returned by lookupHost().

void disconnected()

This signal is emitted when the socket has been disconnected.

SocketState

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

Q_CORE_EXPORT void qDebug(const char *,…)

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…

void stateChanged(QAbstractSocket::SocketState)

This signal is emitted whenever QAbstractSocket's state changes.

The QTimer class provides repetitive and single-shot timers.

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

◆ error() [1/2]

Returns the type of error that last occurred.

See also
state(), errorString()

Definition at line 2803 of file qabstractsocket.cpp.

Referenced by QSocks5SocketEnginePrivate::_q_emitPendingReadNotification(), QSslSocketPrivate::_q_errorSlot(), QHttpNetworkConnectionChannel::_q_readyRead(), QUdpSocket::bind(), QSocks5SocketEngine::bind(), connectToHostImplementation(), QUdpSocket::readDatagram(), QSocks5SocketEnginePrivate::setErrorState(), QSslSocketBackendPrivate::transmit(), waitForBytesWritten(), waitForDisconnected(), waitForReadyRead(), and QUdpSocket::writeDatagram().

2804 {

2805  return d_func()->socketError;

2806 }

◆ error [2/2]

◆ 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 

2223 

2224  if (QSslSocket *socket = qobject_cast<QSslSocket *>(this))

2225  return socket->flush();

2226 #endif

2228  return d->flush();

2229 }

The QSslSocket class provides an SSL encrypted socket for both clients and servers.

#define Q_CHECK_SOCKETENGINE(returnValue)

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

◆ hostFound

void QAbstractSocket::hostFound ( )
signal

◆ isSequential()

bool QAbstractSocket::isSequential ( ) const
virtual

◆ isValid()

bool QAbstractSocket::isValid ( ) const

◆ localAddress()

◆ localPort()

quint16 QAbstractSocket::localPort ( ) const

◆ peerAddress()

◆ peerName()

QString QAbstractSocket::peerName ( ) const

◆ peerPort()

quint16 QAbstractSocket::peerPort ( ) const

◆ proxy()

◆ proxyAuthenticationRequired

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 

2238  if (d->isBuffered && d->readBuffer.isEmpty())

2239 

2240 

2242 

2243 

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]»,

2249 #endif

2250  if (d->readBuffer.isEmpty() && d->socketEngine && d->socketEngine->isValid())

2251  d->socketEngine->setReadNotificationEnabled(true);

2252  return 1;

2253  }

2254 

2255 

2256 

2258  && !d->isBuffered

2259  && d->readBuffer.size() < maxSize

2260  && d->readBufferMaxSize > 0

2261  && maxSize < d->readBufferMaxSize

2262  && d->socketEngine

2263  && d->socketEngine->isValid()) {

2264 

2265 

2266 

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 

2273  d->readBuffer.chop(bytesToRead);

2274  } else {

2275  d->readBuffer.chop(int(bytesToRead — (readBytes < 0 ? qint64(0) : readBytes)));

2276  }

2277  }

2278  }

2279 

2280 

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 

2297 

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 

2309 

2310  if (!d->isBuffered) {

2311  if (!d->socketEngine)

2312  return -1;

2313  if (!d->socketEngine->isValid())

2314  return -1;

2316  return -1;

2317  qint64 readBytes = d->socketEngine->read(data, maxSize);

2318  if (readBytes == -2) {

2319 

2320  return 0;

2321  } else if (readBytes < 0) {

2322  d->socketError = d->socketEngine->error();

2324  d->resetSocketLayer();

2326  } else if (!d->socketEngine->isReadNotificationEnabled()) {

2327 

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 }

Q_DECL_CONSTEXPR const T & qMin(const T &a, const T &b)

Q_CORE_EXPORT void qDebug(const char *,…)

static const char * data(const QByteArray &arr)

const T * ptr(const T &t)

void setErrorString(const QString &errorString)

Sets the human readable description of the last device error that occurred to str.

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 {

2353 }

virtual qint64 readLineData(char *data, qint64 maxlen)

Reads up to maxSize characters into data and returns the number of characters read.

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 }

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 }

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 }

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 }

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 }

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:

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 }

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 

2749 

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 

2761 

2762 

2764  d->socketEngine->setReadNotificationEnabled(true);

2765  }

2766 }

virtual qint64 size() const

For open random-access devices, this function returns the size of the device.

The QSslSocket class provides an SSL encrypted socket for both clients and servers.

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

◆ setSocketDescriptor()

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

1691 #endif

1692 

1693  d->resetSocketLayer();

1695  if (!d->socketEngine) {

1698  return false;

1699  }

1700 #ifndef QT_NO_BEARERMANAGEMENT

1701 

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

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;

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

1728 

1729  return true;

1730 }

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.

static QString tr(const char *sourceText, const char *comment=0, int n=-1)

OpenMode openMode() const

Returns the mode in which the device has been opened; i.e.

void setErrorString(const QString &errorString)

Sets the human readable description of the last device error that occurred to str.

virtual bool open(OpenMode mode)

Opens the device and sets its OpenMode to mode.

QVariant property(const char *name) const

Returns the value of the object's name property.

void stateChanged(QAbstractSocket::SocketState)

This signal is emitted whenever QAbstractSocket's state changes.

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

◆ setSocketError()

void QAbstractSocket::setSocketError ( SocketError  socketError )
protected

◆ setSocketOption()

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

1756  break;

1757 

1760  break;

1761 

1764  break;

1765 

1768  break;

1769  }

1770 }

The QSslSocket class provides an SSL encrypted socket for both clients and servers.

int toInt(bool *ok=0) const

Returns the variant as an int if the variant has type() Int , Bool , ByteArray , Char …

◆ 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

◆ socketOption()

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)

1791 

1792  int ret = -1;

1793  switch (option) {

1796  break;

1797 

1800  break;

1801 

1804  break;

1807  break;

1808  }

1809  if (ret == -1)

1811  else

1813 }

The QVariant class acts like a union for the most common Qt data types.

The QSslSocket class provides an SSL encrypted socket for both clients and servers.

◆ socketType()

◆ state()

Returns the state of the socket.

See also
error()

Definition at line 2773 of file qabstractsocket.cpp.

Referenced by QSocks5SocketEnginePrivate::_q_emitPendingReadNotification(), QHttpNetworkConnectionChannel::_q_readyRead(), QHttpNetworkConnectionChannel::_q_receiveReply(), QHttpPrivate::_q_slotSendRequest(), QHttpNetworkConnectionPrivate::_q_startNextRequest(), QHttpNetworkConnectionChannel::allDone(), QUdpSocket::bind(), QFtpDTP::bytesAvailable(), QHttpNetworkConnectionChannel::close(), QHttpNetworkConnectionChannel::detectPipeliningSupport(), QHttpNetworkConnectionChannel::ensureConnection(), QHttpNetworkConnectionPrivate::fillPipeline(), QDeclarativeDebugConnection::isConnected(), QVNCDirtyMap::QVNCDirtyMap(), QFtpDTP::read(), QFtpDTP::readAll(), QFtpPI::sendCommands(), setSocketState(), QFtpDTP::state(), QSslSocketBackendPrivate::transmit(), waitForBytesWritten(), waitForConnected(), waitForDisconnected(), waitForReadyRead(), QRfbRawEncoder::write(), and QRfbHextileEncoder< SRC >::write().

2774 {

2775  return d_func()->state;

2776 }

◆ stateChanged

◆ 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 

2015  qWarning(«QAbstractSocket::waitForBytesWritten() is not allowed in UnconnectedState»);

2016  return false;

2017  }

2018 

2019  if (d->writeBuffer.isEmpty())

2020  return false;

2021 

2023  stopWatch.start();

2024 

2025 

2028  return false;

2029  }

2030 

2032  bool readyToRead = false;

2033  bool readyToWrite = false;

2034  if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, true, !d->writeBuffer.isEmpty(),

2036  d->socketError = d->socketEngine->error();

2038 #if defined (QABSTRACTSOCKET_DEBUG)

2039  qDebug(«QAbstractSocket::waitForBytesWritten(%i) failed (%i, %s)»,

2040  msecs, d->socketError, errorString().toLatin1().constData());

2041 #endif

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 

2067  return false;

2068  }

2069  return false;

2070 }

QString errorString() const

Returns a human-readable description of the last device error that occurred.

The QElapsedTimer class provides a fast way to calculate elapsed times.

qint64 elapsed() const

Returns the number of milliseconds since this QElapsedTimer was last started.

Q_CORE_EXPORT void qDebug(const char *,…)

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's connection with the host…

void setErrorString(const QString &errorString)

Sets the human readable description of the last device error that occurred to str.

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.

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

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 

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 

1867 

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;

1875  stopWatch.start();

1876 

1878 #if defined (QABSTRACTSOCKET_DEBUG)

1879  qDebug(«QAbstractSocket::waitForConnected(%i) doing host name lookup», msecs);

1880 #endif

1882  d->hostLookupId = -1;

1883 #ifndef QT_NO_BEARERMANAGEMENT

1886  if (v.isValid()) {

1889  } else

1890 #endif

1892  }

1894  return false;

1895 

1896  bool timedOut = true;

1897 #if defined (QABSTRACTSOCKET_DEBUG)

1898  int attempt = 1;

1899 #endif

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 

1921  d->resetSocketLayer();

1923  }

1924 

1925 #if defined (QABSTRACTSOCKET_DEBUG)

1926  qDebug(«QAbstractSocket::waitForConnected(%i) == %s», msecs,

1928 #endif

1930  return false;

1931  if (wasPendingClose)

1933  return true;

1934 }

The QVariant class acts like a union for the most common Qt data types.

static void abortHostLookup(int lookupId)

Aborts the host lookup with the ID id, as returned by lookupHost().

The QSslSocket class provides an SSL encrypted socket for both clients and servers.

static QString tr(const char *sourceText, const char *comment=0, int n=-1)

The QElapsedTimer class provides a fast way to calculate elapsed times.

qint64 elapsed() const

Returns the number of milliseconds since this QElapsedTimer was last started.

Q_CORE_EXPORT void qDebug(const char *,…)

static QHostInfo fromName(const QString &hostName, QSharedPointer< QNetworkSession > networkSession)

#define QT_CONNECT_TIMEOUT

static QHostInfo fromName(const QString &name)

Looks up the IP address(es) for the given host name.

void setErrorString(const QString &errorString)

Sets the human readable description of the last device error that occurred to str.

T qvariant_cast(const QVariant &)

QVariant property(const char *name) const

Returns the value of the object's name property.

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

socket->waitForDisconnected(1000))

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 

2093 

2094  if (QSslSocket *socket = qobject_cast<QSslSocket *>(this))

2095  return socket->waitForDisconnected(msecs);

2096 #endif

2097 

2098 

2100  qWarning(«QAbstractSocket::waitForDisconnected() is not allowed in UnconnectedState»);

2101  return false;

2102  }

2103 

2105  stopWatch.start();

2106 

2107 

2110  return false;

2112  return true;

2113  }

2114 

2116  bool readyToRead = false;

2117  bool readyToWrite = false;

2118  if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, state() == ConnectedState,

2119  !d->writeBuffer.isEmpty(),

2121  d->socketError = d->socketEngine->error();

2123 #if defined (QABSTRACTSOCKET_DEBUG)

2124  qDebug(«QAbstractSocket::waitForReadyRead(%i) failed (%i, %s)»,

2125  msecs, d->socketError, errorString().toLatin1().constData());

2126 #endif

2130  return false;

2131  }

2132 

2133  if (readyToRead)

2134  d->canReadNotification();

2135  if (readyToWrite)

2136  d->canWriteNotification();

2137 

2139  return true;

2140  }

2141  return false;

2142 }

QString errorString() const

Returns a human-readable description of the last device error that occurred.

The QSslSocket class provides an SSL encrypted socket for both clients and servers.

The QElapsedTimer class provides a fast way to calculate elapsed times.

qint64 elapsed() const

Returns the number of milliseconds since this QElapsedTimer was last started.

Q_CORE_EXPORT void qDebug(const char *,…)

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's connection with the host…

void setErrorString(const QString &errorString)

Sets the human readable description of the last device error that occurred to str.

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.

◆ 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 

1957 

1958 

1959 

1960  return false;

1961  }

1962 

1964  stopWatch.start();

1965 

1966 

1969  return false;

1970  }

1971 

1973  do {

1974  bool readyToRead = false;

1975  bool readyToWrite = false;

1976  if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, true, !d->writeBuffer.isEmpty(),

1978  d->socketError = d->socketEngine->error();

1980 #if defined (QABSTRACTSOCKET_DEBUG)

1981  qDebug(«QAbstractSocket::waitForReadyRead(%i) failed (%i, %s)»,

1982  msecs, d->socketError, errorString().toLatin1().constData());

1983 #endif

1987  return false;

1988  }

1989 

1990  if (readyToRead) {

1991  if (d->canReadNotification())

1992  return true;

1993  }

1994 

1995  if (readyToWrite)

1996  d->canWriteNotification();

1997 

1999  return false;

2001  return false;

2002 }

QString errorString() const

Returns a human-readable description of the last device error that occurred.

The QElapsedTimer class provides a fast way to calculate elapsed times.

qint64 elapsed() const

Returns the number of milliseconds since this QElapsedTimer was last started.

Q_CORE_EXPORT void qDebug(const char *,…)

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's connection with the host…

void setErrorString(const QString &errorString)

Sets the human readable description of the last device error that occurred to str.

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 {

2363  return -1;

2364  }

2365 

2366  if (!d->isBuffered && d->socketType == TcpSocket && d->writeBuffer.isEmpty()) {

2367 

2369  if (written < 0) {

2370  d->socketError = d->socketEngine->error();

2372  return written;

2373  } else if (written < size) {

2374 

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;

2381  } else if (!d->isBuffered && d->socketType != TcpSocket) {

2382 

2384  if (written < 0) {

2385  d->socketError = d->socketEngine->error();

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,

2394  size, written);

2395 #endif

2396  if (written >= 0)

2398  return written;

2399  }

2400 

2401 

2402 

2403 

2404 

2405 

2406 

2407  char *ptr = d->writeBuffer.reserve(size);

2408  if (size == 1)

2409  *ptr = *data;

2410  else

2411  memcpy(ptr, data, size);

2412 

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 }

virtual qint64 size() const

For open random-access devices, this function returns the size of the device.

Q_DECL_CONSTEXPR const T & qMin(const T &a, const T &b)

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.

Q_CORE_EXPORT void qDebug(const char *,…)

static const char * data(const QByteArray &arr)

const T * ptr(const T &t)

void setErrorString(const QString &errorString)

Sets the human readable description of the last device error that occurred to str.

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


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

  • /src/network/socket/qabstractsocket.h
  • /src/network/socket/qabstractsocket.cpp

QAbstractSocket Class Reference
[QtNetwork module]

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

Inherits QIODevice.

Inherited by QTcpSocket and QUdpSocket.

Types

  • enum NetworkLayerProtocol { IPv4Protocol, IPv6Protocol, UnknownNetworkLayerProtocol }

  • enum SocketError { ConnectionRefusedError, RemoteHostClosedError, HostNotFoundError, SocketAccessError, …, UnknownSocketError }

  • enum SocketOption { LowDelayOption, KeepAliveOption, MulticastTtlOption, MulticastLoopbackOption }

  • enum SocketState { UnconnectedState, HostLookupState, ConnectingState, ConnectedState, …, ClosingState }

  • enum SocketType { TcpSocket, UdpSocket, UnknownSocketType }

Methods

  • __init__ (self, SocketType socketType, QObject parent)

  • connectToHost (self, QString hostName, int port, QIODevice.OpenMode mode = QIODevice.ReadWrite)

  • connectToHost (self, QHostAddress address, int port, QIODevice.OpenMode mode = QIODevice.ReadWrite)

  • connectToHostImplementation (self, QString hostName, int port, QIODevice.OpenMode mode = QIODevice.ReadWrite)

  • SocketError error (self)

  • QNetworkProxy proxy (self)

  • setProxy (self, QNetworkProxy networkProxy)

  • bool setSocketDescriptor (self, int socketDescriptor, SocketState state = QAbstractSocket.ConnectedState, QIODevice.OpenMode mode = QIODevice.ReadWrite)

  • QVariant socketOption (self, SocketOption option)

  • SocketState state (self)

Qt Signals

  • void error (QAbstractSocket::SocketError)


Detailed Description

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

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:

  • Instantiate QTcpSocket or
    QUdpSocket.
  • Create a native socket descriptor, instantiate QAbstractSocket,
    and call setSocketDescriptor()
    to wrap the native socket.

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:

  • waitForConnected()
    blocks until a connection has been established.
  • waitForReadyRead()
    blocks until new data is available for reading.
  • waitForBytesWritten()
    blocks until one payload of data has been written to the
    socket.
  • waitForDisconnected()
    blocks until the connection has closed.

We show an example:

     int numRead = 0, numReadTotal = 0;
     char buffer[50];

     forever {
         numRead  = socket.read(buffer, 50);

         

         numReadTotal += numRead;
         if (numRead == 0 && !socket.waitForReadyRead())
             break;
     }

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


Type Documentation

QAbstractSocket.NetworkLayerProtocol

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

Constant Value Description
QAbstractSocket.IPv4Protocol 0 IPv4
QAbstractSocket.IPv6Protocol 1 IPv6
QAbstractSocket.UnknownNetworkLayerProtocol -1 Other than IPv4 and IPv6

See also QHostAddress.protocol().

QAbstractSocket.SocketError

This enum describes the socket errors that can occur.

Constant Value Description
QAbstractSocket.ConnectionRefusedError 0 The connection was refused by the peer (or
timed out).
QAbstractSocket.RemoteHostClosedError 1 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.
QAbstractSocket.HostNotFoundError 2 The host address was not found.
QAbstractSocket.SocketAccessError 3 The socket operation failed because the
application lacked the required privileges.
QAbstractSocket.SocketResourceError 4 The local system ran out of resources (e.g.,
too many sockets).
QAbstractSocket.SocketTimeoutError 5 The socket operation timed out.
QAbstractSocket.DatagramTooLargeError 6 The datagram was larger than the operating
system’s limit (which can be as low as 8192 bytes).
QAbstractSocket.NetworkError 7 An error occurred with the network (e.g., the
network cable was accidentally plugged out).
QAbstractSocket.AddressInUseError 8 The address specified to QUdpSocket.bind() is already in use and
was set to be exclusive.
QAbstractSocket.SocketAddressNotAvailableError 9 The address specified to QUdpSocket.bind() does not belong to
the host.
QAbstractSocket.UnsupportedSocketOperationError 10 The requested socket operation is not
supported by the local operating system (e.g., lack of IPv6
support).
QAbstractSocket.ProxyAuthenticationRequiredError 12 The socket is using a proxy, and the proxy
requires authentication.
QAbstractSocket.SslHandshakeFailedError 13 The SSL/TLS handshake failed, so the
connection was closed (only used in QSslSocket) (This value was introduced in
4.4.)
QAbstractSocket.UnfinishedSocketOperationError 11 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.)
QAbstractSocket.ProxyConnectionRefusedError 14 Could not contact the proxy server because the
connection to that server was denied (This value was introduced in
4.5.)
QAbstractSocket.ProxyConnectionClosedError 15 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.)
QAbstractSocket.ProxyConnectionTimeoutError 16 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.)
QAbstractSocket.ProxyNotFoundError 17 The proxy address set with setProxy() (or the application
proxy) was not found. (This value was introduced in 4.5.)
QAbstractSocket.ProxyProtocolError 18 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.)
QAbstractSocket.UnknownSocketError -1 An unidentified error occurred.

See also QAbstractSocket.error().

QAbstractSocket.SocketOption

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

Constant Value Description
QAbstractSocket.LowDelayOption 0 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.
QAbstractSocket.KeepAliveOption 1 Set this to 1 to enable the SO_KEEPALIVE
socket option
QAbstractSocket.MulticastTtlOption 2 Set this to an integer value to set
IP_MULTICAST_TTL (TTL for multicast datagrams) socket option.
QAbstractSocket.MulticastLoopbackOption 3 Set this to 1 to enable the IP_MULTICAST_LOOP
(multicast loopback) socket option.

This enum was introduced or modified in Qt 4.6.

See also QAbstractSocket.setSocketOption()
and QAbstractSocket.socketOption().

QAbstractSocket.SocketState

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

Constant Value Description
QAbstractSocket.UnconnectedState 0 The socket is not connected.
QAbstractSocket.HostLookupState 1 The socket is performing a host name
lookup.
QAbstractSocket.ConnectingState 2 The socket has started establishing a
connection.
QAbstractSocket.ConnectedState 3 A connection is established.
QAbstractSocket.BoundState 4 The socket is bound to an address and port
(for servers).
QAbstractSocket.ClosingState 6 The socket is about to close (data may still
be waiting to be written).
QAbstractSocket.ListeningState 5 For internal use only.

See also QAbstractSocket.state().

QAbstractSocket.SocketType

This enum describes the transport layer protocol.

Constant Value Description
QAbstractSocket.TcpSocket 0 TCP
QAbstractSocket.UdpSocket 1 UDP
QAbstractSocket.UnknownSocketType -1 Other than TCP and UDP

See also QAbstractSocket.socketType().


Method Documentation

QAbstractSocket.__init__ (self, SocketType socketType, QObject parent)

The parent argument, if not None, causes self to be owned by Qt instead of PyQt.

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

See also socketType(), QTcpSocket, and QUdpSocket.

QAbstractSocket.abort (self)

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

bool QAbstractSocket.atEnd (self)

Reimplemented from QIODevice.atEnd().

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

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

  
  void SocketClass.readyReadSlot()
  {
      while (!socket.atEnd()) {
          QByteArray data = socket.read(100);
          ....
      }
  }

See also bytesAvailable() and
readyRead().

int QAbstractSocket.bytesAvailable (self)

Reimplemented from QIODevice.bytesAvailable().

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

See also bytesToWrite() and read().

int QAbstractSocket.bytesToWrite (self)

Reimplemented from QIODevice.bytesToWrite().

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

bool QAbstractSocket.canReadLine (self)

Reimplemented from QIODevice.canReadLine().

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

See also readLine().

QAbstractSocket.close (self)

Reimplemented from QIODevice.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.

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

See also abort().

QAbstractSocket.connectToHost (self, QString hostName, int port, QIODevice.OpenMode mode = QIODevice.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(), and waitForConnected().

QAbstractSocket.connectToHost (self, QHostAddress address, int port, QIODevice.OpenMode mode = QIODevice.ReadWrite)

This is an overloaded function.

Attempts to make a connection to address on port
port.

QAbstractSocket.connectToHostImplementation (self, QString hostName, int port, QIODevice.OpenMode mode = QIODevice.ReadWrite)

This method is also a Qt slot with the C++ signature void connectToHostImplementation(const QString&,quint16,QIODevice::OpenMode = QIODevice.ReadWrite).

Contains the implementation of connectToHost().

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

This function was introduced in Qt 4.1.

QAbstractSocket.disconnectFromHost (self)

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

QAbstractSocket.disconnectFromHostImplementation (self)

This method is also a Qt slot with the C++ signature void disconnectFromHostImplementation().

Contains the implementation of disconnectFromHost().

This function was introduced in Qt 4.1.

SocketError QAbstractSocket.error (self)

Returns the type of error that last occurred.

See also state()
and errorString().

bool QAbstractSocket.flush (self)

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

bool QAbstractSocket.isSequential (self)

Reimplemented from QIODevice.isSequential().

bool QAbstractSocket.isValid (self)

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

QHostAddress QAbstractSocket.localAddress (self)

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(), and setLocalAddress().

int QAbstractSocket.localPort (self)

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

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

QHostAddress QAbstractSocket.peerAddress (self)

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

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

QString QAbstractSocket.peerName (self)

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

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

int QAbstractSocket.peerPort (self)

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

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

QNetworkProxy QAbstractSocket.proxy (self)

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

This function was introduced in Qt 4.1.

See also setProxy(), QNetworkProxy, and QNetworkProxyFactory.

int QAbstractSocket.readBufferSize (self)

Returns the size of the internal read buffer. This limits the
amount of data that the client can receive before you call read() or readAll().

A read buffer size of 0 (the default) means that the buffer has
no size limit, ensuring that no data is lost.

See also setReadBufferSize()
and read().

str QAbstractSocket.readData (self, int maxlen)

Reimplemented from QIODevice.readData().

str QAbstractSocket.readLineData (self, int maxlen)

Reimplemented from QIODevice.readLineData().

QAbstractSocket.setLocalAddress (self, QHostAddress address)

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

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

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

This function was introduced in Qt 4.1.

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

QAbstractSocket.setLocalPort (self, int port)

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

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

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

This function was introduced in Qt 4.1.

See also localPort(), localAddress(), setLocalAddress(), and
setPeerPort().

QAbstractSocket.setPeerAddress (self, QHostAddress address)

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

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

This function was introduced in Qt 4.1.

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

QAbstractSocket.setPeerName (self, QString name)

Sets the host name of the remote peer to name.

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

This function was introduced in Qt 4.1.

See also peerName().

QAbstractSocket.setPeerPort (self, int port)

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

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

This function was introduced in Qt 4.1.

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

QAbstractSocket.setProxy (self, QNetworkProxy networkProxy)

Sets the explicit network proxy for this socket to
networkProxy.

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

 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.

This function was introduced in Qt 4.1.

See also proxy(), QNetworkProxy, and QNetworkProxyFactory.queryProxy().

QAbstractSocket.setReadBufferSize (self, int 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() and
read().

bool QAbstractSocket.setSocketDescriptor (self, int socketDescriptor, SocketState state = QAbstractSocket.ConnectedState, QIODevice.OpenMode mode = QIODevice.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().

QAbstractSocket.setSocketError (self, SocketError socketError)

Sets the type of error that last occurred to
socketError.

See also setSocketState() and
setErrorString().

QAbstractSocket.setSocketOption (self, SocketOption option, QVariant value)

Sets the given option to the value described by
value.

This function was introduced in Qt 4.6.

See also socketOption().

QAbstractSocket.setSocketState (self, SocketState state)

Sets the state of the socket to state.

See also state().

int QAbstractSocket.socketDescriptor (self)

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

QVariant QAbstractSocket.socketOption (self, SocketOption option)

Returns the value of the option option.

This function was introduced in Qt 4.6.

See also setSocketOption().

SocketType QAbstractSocket.socketType (self)

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

See also QTcpSocket and
QUdpSocket.

SocketState QAbstractSocket.state (self)

Returns the state of the socket.

See also error().

bool QAbstractSocket.waitForBytesWritten (self, int msecs = 30000)

Reimplemented from QIODevice.waitForBytesWritten().

bool QAbstractSocket.waitForConnected (self, 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.

Note: Multiple calls to this functions do not accumulate
the time. If the function times out, the connecting process will be
aborted.

See also connectToHost() and
connected().

bool QAbstractSocket.waitForDisconnected (self, 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()
and close().

bool QAbstractSocket.waitForReadyRead (self, int msecs = 30000)

Reimplemented from QIODevice.waitForReadyRead().

This function blocks until new data is available for reading and
the readyRead() signal has
been emitted. The function will timeout after msecs
milliseconds; the default timeout is 30000 milliseconds.

The function returns true if 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().

int QAbstractSocket.writeData (self, str data)

Reimplemented from QIODevice.writeData().


Qt Signal Documentation

void connected ()

This is the default overload of this 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() and
disconnected().

void disconnected ()

This is the default overload of this 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(),
and abort().

void error (QAbstractSocket::SocketError)

This is the default overload of this 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(), and Creating Custom Qt Types.

void hostFound ()

This is the default overload of this 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().

void proxyAuthenticationRequired (const QNetworkProxy&,QAuthenticator*)

This is the default overload of this signal.

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

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.

This function was introduced in Qt 4.3.

See also QAuthenticator
and QNetworkProxy.

void stateChanged (QAbstractSocket::SocketState)

This is the default overload of this 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()
and Creating Custom Qt Types.


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

Header: #include <QAbstractSocket>
CMake: find_package(Qt6 COMPONENTS Network REQUIRED) target_link_libraries(mytarget PRIVATE Qt6::Network)
qmake: QT += network
Inherits: QIODevice
Inherited By:

QTcpSocket and QUdpSocket

  • List of all members, including inherited members

Note: All functions in this class are reentrant.

Public Types

enum BindFlag { ShareAddress, DontShareAddress, ReuseAddressHint, DefaultForPlatform }
flags BindMode
enum NetworkLayerProtocol { IPv4Protocol, IPv6Protocol, AnyIPProtocol, UnknownNetworkLayerProtocol }
enum PauseMode { PauseNever, PauseOnSslErrors }
flags PauseModes
enum SocketError { ConnectionRefusedError, RemoteHostClosedError, HostNotFoundError, SocketAccessError, SocketResourceError, …, UnknownSocketError }
enum SocketOption { LowDelayOption, KeepAliveOption, MulticastTtlOption, MulticastLoopbackOption, TypeOfServiceOption, …, PathMtuSocketOption }
enum SocketState { UnconnectedState, HostLookupState, ConnectingState, ConnectedState, BoundState, …, ListeningState }
enum SocketType { TcpSocket, UdpSocket, SctpSocket, UnknownSocketType }

Public Functions

QAbstractSocket(QAbstractSocket::SocketType socketType, QObject *parent)
virtual ~QAbstractSocket()
void abort()
virtual bool bind(const QHostAddress &address, quint16 port = 0, QAbstractSocket::BindMode mode = DefaultForPlatform)
bool bind(quint16 port = 0, QAbstractSocket::BindMode mode = DefaultForPlatform)
virtual void connectToHost(const QString &hostName, quint16 port, QIODeviceBase::OpenMode openMode = ReadWrite, QAbstractSocket::NetworkLayerProtocol protocol = AnyIPProtocol)
void connectToHost(const QHostAddress &address, quint16 port, QIODeviceBase::OpenMode openMode = ReadWrite)
virtual void disconnectFromHost()
QAbstractSocket::SocketError error() const
bool flush()
bool isValid() const
QHostAddress localAddress() const
quint16 localPort() const
QAbstractSocket::PauseModes pauseMode() const
QHostAddress peerAddress() const
QString peerName() const
quint16 peerPort() const
QString protocolTag() const
QNetworkProxy proxy() const
qint64 readBufferSize() const
virtual void resume()
void setPauseMode(QAbstractSocket::PauseModes pauseMode)
void setProtocolTag(const QString &tag)
void setProxy(const QNetworkProxy &networkProxy)
virtual void setReadBufferSize(qint64 size)
virtual bool setSocketDescriptor(qintptr socketDescriptor, QAbstractSocket::SocketState socketState = ConnectedState, QIODeviceBase::OpenMode openMode = ReadWrite)
virtual void setSocketOption(QAbstractSocket::SocketOption option, const QVariant &value)
virtual qintptr socketDescriptor() const
virtual QVariant socketOption(QAbstractSocket::SocketOption option)
QAbstractSocket::SocketType socketType() const
QAbstractSocket::SocketState state() const
virtual bool waitForConnected(int msecs = 30000)
virtual bool waitForDisconnected(int msecs = 30000)

Reimplemented Public Functions

virtual qint64 bytesAvailable() const override
virtual qint64 bytesToWrite() const override
virtual void close() override
virtual bool isSequential() const override
virtual bool waitForBytesWritten(int msecs = 30000) override
virtual bool waitForReadyRead(int msecs = 30000) override

Signals

void connected()
void disconnected()
void errorOccurred(QAbstractSocket::SocketError socketError)
void hostFound()
void proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator)
void stateChanged(QAbstractSocket::SocketState socketState)

Protected Functions

void setLocalAddress(const QHostAddress &address)
void setLocalPort(quint16 port)
void setPeerAddress(const QHostAddress &address)
void setPeerName(const QString &name)
void setPeerPort(quint16 port)
void setSocketError(QAbstractSocket::SocketError socketError)
void setSocketState(QAbstractSocket::SocketState state)

Reimplemented Protected Functions

virtual qint64 readData(char *data, qint64 maxSize) override
virtual qint64 readLineData(char *data, qint64 maxlen) override
virtual qint64 skipData(qint64 maxSize) override
virtual qint64 writeData(const char *data, qint64 size) override

Detailed Description

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:

  • Instantiate QTcpSocket or QUdpSocket.
  • Create a native socket descriptor, instantiate QAbstractSocket, and call setSocketDescriptor() to wrap the native socket.

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

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

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

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

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

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

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

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

  • waitForConnected() blocks until a connection has been established.
  • waitForReadyRead() blocks until new data is available for reading.
  • waitForBytesWritten() blocks until one payload of data has been written to the socket.
  • waitForDisconnected() blocks until the connection has closed.

We show an example:

    int numRead = 0, numReadTotal = 0;
    char buffer[50];

    forever {
        numRead  = socket.read(buffer, 50);

        // do whatever with array

        numReadTotal += numRead;
        if (numRead == 0 && !socket.waitForReadyRead())
            break;
    }

If 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 fortuneclient and blockingfortuneclient examples for an overview of both approaches.

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

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

See also QNetworkAccessManager and QTcpServer.

Member Type Documentation

[since 5.0] enum QAbstractSocket::BindFlagflags QAbstractSocket::BindMode

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

Constant Value Description
QAbstractSocket::ShareAddress 0x1 Allow other services to bind to the same address and port. This is useful when multiple processes share the load of a single service by listening to the same address and port (e.g., a web server with several pre-forked listeners can greatly improve response time). However, because any service is allowed to rebind, this option is subject to certain security considerations. Note that by combining this option with ReuseAddressHint, you will also allow your service to rebind an existing shared address. On Unix, this is equivalent to the SO_REUSEADDR socket option. On Windows, this is the default behavior, so this option is ignored.
QAbstractSocket::DontShareAddress 0x2 Bind the address and port exclusively, so that no other services are allowed to rebind. By passing this option to QAbstractSocket::bind(), you are guaranteed that on successs, your service is the only one that listens to the address and port. No services are allowed to rebind, even if they pass ReuseAddressHint. This option provides more security than ShareAddress, but on certain operating systems, it requires you to run the server with administrator privileges. On Unix and macOS, not sharing is the default behavior for binding an address and port, so this option is ignored. On Windows, this option uses the SO_EXCLUSIVEADDRUSE socket option.
QAbstractSocket::ReuseAddressHint 0x4 Provides a hint to QAbstractSocket that it should try to rebind the service even if the address and port are already bound by another socket. On Windows and Unix, this is equivalent to the SO_REUSEADDR socket option.
QAbstractSocket::DefaultForPlatform 0x0 The default option for the current platform. On Unix and macOS, this is equivalent to (DontShareAddress + ReuseAddressHint), and on Windows, it is equivalent to ShareAddress.

This enum was introduced or modified in Qt 5.0.

The BindMode type is a typedef for QFlags<BindFlag>. It stores an OR combination of BindFlag values.

enum QAbstractSocket::NetworkLayerProtocol

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

Constant Value Description
QAbstractSocket::IPv4Protocol 0 IPv4
QAbstractSocket::IPv6Protocol 1 IPv6
QAbstractSocket::AnyIPProtocol 2 Either IPv4 or IPv6
QAbstractSocket::UnknownNetworkLayerProtocol -1 Other than IPv4 and IPv6

See also QHostAddress::protocol().

[since 5.0] enum QAbstractSocket::PauseModeflags QAbstractSocket::PauseModes

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

Constant Value Description
QAbstractSocket::PauseNever 0x0 Do not pause data transfer on the socket. This is the default and matches the behavior of Qt 4.
QAbstractSocket::PauseOnSslErrors 0x1 Pause data transfer on the socket upon receiving an SSL error notification. I.E. QSslSocket::sslErrors().

This enum was introduced or modified in Qt 5.0.

The PauseModes type is a typedef for QFlags<PauseMode>. It stores an OR combination of PauseMode values.

enum QAbstractSocket::SocketError

This enum describes the socket errors that can occur.

Constant Value Description
QAbstractSocket::ConnectionRefusedError 0 The connection was refused by the peer (or timed out).
QAbstractSocket::RemoteHostClosedError 1 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.
QAbstractSocket::HostNotFoundError 2 The host address was not found.
QAbstractSocket::SocketAccessError 3 The socket operation failed because the application lacked the required privileges.
QAbstractSocket::SocketResourceError 4 The local system ran out of resources (e.g., too many sockets).
QAbstractSocket::SocketTimeoutError 5 The socket operation timed out.
QAbstractSocket::DatagramTooLargeError 6 The datagram was larger than the operating system’s limit (which can be as low as 8192 bytes).
QAbstractSocket::NetworkError 7 An error occurred with the network (e.g., the network cable was accidentally plugged out).
QAbstractSocket::AddressInUseError 8 The address specified to QAbstractSocket::bind() is already in use and was set to be exclusive.
QAbstractSocket::SocketAddressNotAvailableError 9 The address specified to QAbstractSocket::bind() does not belong to the host.
QAbstractSocket::UnsupportedSocketOperationError 10 The requested socket operation is not supported by the local operating system (e.g., lack of IPv6 support).
QAbstractSocket::ProxyAuthenticationRequiredError 12 The socket is using a proxy, and the proxy requires authentication.
QAbstractSocket::SslHandshakeFailedError 13 The SSL/TLS handshake failed, so the connection was closed (only used in QSslSocket)
QAbstractSocket::UnfinishedSocketOperationError 11 Used by QAbstractSocketEngine only, The last operation attempted has not finished yet (still in progress in the background).
QAbstractSocket::ProxyConnectionRefusedError 14 Could not contact the proxy server because the connection to that server was denied
QAbstractSocket::ProxyConnectionClosedError 15 The connection to the proxy server was closed unexpectedly (before the connection to the final peer was established)
QAbstractSocket::ProxyConnectionTimeoutError 16 The connection to the proxy server timed out or the proxy server stopped responding in the authentication phase.
QAbstractSocket::ProxyNotFoundError 17 The proxy address set with setProxy() (or the application proxy) was not found.
QAbstractSocket::ProxyProtocolError 18 The connection negotiation with the proxy server failed, because the response from the proxy server could not be understood.
QAbstractSocket::OperationError 19 An operation was attempted while the socket was in a state that did not permit it.
QAbstractSocket::SslInternalError 20 The SSL library being used reported an internal error. This is probably the result of a bad installation or misconfiguration of the library.
QAbstractSocket::SslInvalidUserDataError 21 Invalid data (certificate, key, cypher, etc.) was provided and its use resulted in an error in the SSL library.
QAbstractSocket::TemporaryError 22 A temporary error occurred (e.g., operation would block and socket is non-blocking).
QAbstractSocket::UnknownSocketError -1 An unidentified error occurred.

See also QAbstractSocket::error() and QAbstractSocket::errorOccurred().

enum QAbstractSocket::SocketOption

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

Constant Value Description
QAbstractSocket::LowDelayOption 0 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.
QAbstractSocket::KeepAliveOption 1 Set this to 1 to enable the SO_KEEPALIVE socket option
QAbstractSocket::MulticastTtlOption 2 Set this to an integer value to set IP_MULTICAST_TTL (TTL for multicast datagrams) socket option.
QAbstractSocket::MulticastLoopbackOption 3 Set this to 1 to enable the IP_MULTICAST_LOOP (multicast loopback) socket option.
QAbstractSocket::TypeOfServiceOption 4 This option is not supported on Windows. This maps to the IP_TOS socket option. For possible values, see table below.
QAbstractSocket::SendBufferSizeSocketOption 5 Sets the socket send buffer size in bytes at the OS level. This maps to the SO_SNDBUF socket option. This option does not affect the QIODevice or QAbstractSocket buffers. This enum value has been introduced in Qt 5.3.
QAbstractSocket::ReceiveBufferSizeSocketOption 6 Sets the socket receive buffer size in bytes at the OS level. This maps to the SO_RCVBUF socket option. This option does not affect the QIODevice or QAbstractSocket buffers (see setReadBufferSize()). This enum value has been introduced in Qt 5.3.
QAbstractSocket::PathMtuSocketOption 7 Retrieves the Path Maximum Transmission Unit (PMTU) value currently known by the IP stack, if any. Some IP stacks also allow setting the MTU for transmission. This enum value was introduced in Qt 5.11.

Possible values for TypeOfServiceOption are:

Value Description
224 Network control
192 Internetwork control
160 CRITIC/ECP
128 Flash override
96 Flash
64 Immediate
32 Priority
0 Routine

See also QAbstractSocket::setSocketOption() and QAbstractSocket::socketOption().

enum QAbstractSocket::SocketState

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

Constant Value Description
QAbstractSocket::UnconnectedState 0 The socket is not connected.
QAbstractSocket::HostLookupState 1 The socket is performing a host name lookup.
QAbstractSocket::ConnectingState 2 The socket has started establishing a connection.
QAbstractSocket::ConnectedState 3 A connection is established.
QAbstractSocket::BoundState 4 The socket is bound to an address and port.
QAbstractSocket::ClosingState 6 The socket is about to close (data may still be waiting to be written).
QAbstractSocket::ListeningState 5 For internal use only.

See also QAbstractSocket::state().

enum QAbstractSocket::SocketType

This enum describes the transport layer protocol.

Constant Value Description
QAbstractSocket::TcpSocket 0 TCP
QAbstractSocket::UdpSocket 1 UDP
QAbstractSocket::SctpSocket 2 SCTP
QAbstractSocket::UnknownSocketType -1 Other than TCP, UDP and SCTP

See also QAbstractSocket::socketType().

Member Function Documentation

QAbstractSocket::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, and QUdpSocket.

[signal] void QAbstractSocket::connected()

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

[signal] void QAbstractSocket::disconnected()

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(), and abort().

[signal, since 5.15] void QAbstractSocket::errorOccurred(QAbstractSocket::SocketError socketError)

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

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

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

This function was introduced in Qt 5.15.

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

[signal] void QAbstractSocket::hostFound()

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

[signal] void QAbstractSocket::proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator)

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 and QNetworkProxy.

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

This signal is emitted whenever QAbstractSocket’s state changes. The socketState parameter is the new state.

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

See also state() and Creating Custom Qt Types.

[virtual] QAbstractSocket::~QAbstractSocket()

Destroys the socket.

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

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

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

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

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

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

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

This function was introduced in Qt 5.0.

[since 5.0] bool QAbstractSocket::bind(quint16 port = 0, QAbstractSocket::BindMode mode = DefaultForPlatform)

This is an overloaded function.

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

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

This function was introduced in Qt 5.0.

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

Reimplements: QIODevice::bytesAvailable() const.

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

See also bytesToWrite() and read().

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

Reimplements: QIODevice::bytesToWrite() const.

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

[override virtual] void QAbstractSocket::close()

Reimplements: QIODevice::close().

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

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

See also abort().

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

Attempts to make a connection to hostName on the given port. The protocol parameter can be used to specify which network protocol to use (eg. IPv4 or IPv6).

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

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

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

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

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

This is an overloaded function.

Attempts to make a connection to address on port port.

[virtual] 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().

QAbstractSocket::SocketError QAbstractSocket::error() const

Returns the type of error that last occurred.

See also state() and errorString().

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

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

Reimplements: QIODevice::isSequential() const.

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

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(), and setLocalAddress().

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(), and setLocalPort().

[since 5.0] QAbstractSocket::PauseModes QAbstractSocket::pauseMode() const

Returns the pause mode of this socket.

This function was introduced in Qt 5.0.

See also setPauseMode() and resume().

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(), and setPeerAddress().

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(), and setPeerName().

quint16 QAbstractSocket::peerPort() const

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

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

[since 5.13] QString QAbstractSocket::protocolTag() const

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

This function was introduced in Qt 5.13.

See also setProtocolTag() and QNetworkProxyQuery.

QNetworkProxy QAbstractSocket::proxy() const

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

See also setProxy(), QNetworkProxy, and QNetworkProxyFactory.

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

[override virtual protected] qint64 QAbstractSocket::readData(char *data, qint64 maxSize)

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

[override virtual protected] qint64 QAbstractSocket::readLineData(char *data, qint64 maxlen)

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

[virtual, since 5.0] void QAbstractSocket::resume()

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

This function was introduced in Qt 5.0.

See also pauseMode() and setPauseMode().

[protected] void QAbstractSocket::setLocalAddress(const QHostAddress &address)

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

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

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

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

[protected] void QAbstractSocket::setLocalPort(quint16 port)

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

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

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

See also localPort(), localAddress(), setLocalAddress(), and setPeerPort().

[since 5.0] void QAbstractSocket::setPauseMode(QAbstractSocket::PauseModes pauseMode)

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

This function was introduced in Qt 5.0.

See also pauseMode() and resume().

[protected] void QAbstractSocket::setPeerAddress(const QHostAddress &address)

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

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

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

[protected] void QAbstractSocket::setPeerName(const QString &name)

Sets the host name of the remote peer to name.

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

See also peerName().

[protected] void QAbstractSocket::setPeerPort(quint16 port)

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

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

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

[since 5.13] void QAbstractSocket::setProtocolTag(const QString &tag)

Sets the protocol tag for this socket to tag.

This function was introduced in Qt 5.13.

See also protocolTag().

void QAbstractSocket::setProxy(const QNetworkProxy &networkProxy)

Sets the explicit network proxy for this socket to networkProxy.

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

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, and QNetworkProxyFactory::queryProxy().

[virtual] 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() and read().

[virtual] bool QAbstractSocket::setSocketDescriptor(qintptr socketDescriptor, QAbstractSocket::SocketState socketState = ConnectedState, QIODeviceBase::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. Read and write buffers are cleared, discarding any pending data.

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

See also socketDescriptor().

[protected] void QAbstractSocket::setSocketError(QAbstractSocket::SocketError socketError)

Sets the type of error that last occurred to socketError.

See also setSocketState() and setErrorString().

[virtual] void QAbstractSocket::setSocketOption(QAbstractSocket::SocketOption option, const QVariant &value)

Sets the given option to the value described by value.

Note: On Windows Runtime, QAbstractSocket::KeepAliveOption must be set before the socket is connected.

See also socketOption().

[protected] void QAbstractSocket::setSocketState(QAbstractSocket::SocketState state)

Sets the state of the socket to state.

See also state().

[override virtual protected] qint64 QAbstractSocket::skipData(qint64 maxSize)

Reimplements: QIODevice::skipData(qint64 maxSize).

[virtual] qintptr 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().

[virtual] QVariant QAbstractSocket::socketOption(QAbstractSocket::SocketOption option)

Returns the value of the option option.

See also setSocketOption().

QAbstractSocket::SocketType QAbstractSocket::socketType() const

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

See also QTcpSocket and QUdpSocket.

QAbstractSocket::SocketState QAbstractSocket::state() const

Returns the state of the socket.

See also error().

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

Reimplements: QIODevice::waitForBytesWritten(int msecs).

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

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

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

See also waitForReadyRead().

[virtual] 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.

Note: Multiple calls to this functions do not accumulate the time. If the function times out, the connecting process will be aborted.

Note: This function may fail randomly on Windows. Consider using the event loop and the connected() signal if your software will run on Windows.

See also connectToHost() and connected().

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

Waits until the socket has disconnected, up to msecs milliseconds. If the connection was successfully disconnected, this function returns true; otherwise it returns false (if the operation timed out, if an error occurred, or if this QAbstractSocket is already disconnected). In the case where it returns false, you can call error() to determine the cause of the error.

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

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

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

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

See also disconnectFromHost() and close().

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

Reimplements: QIODevice::waitForReadyRead(int msecs).

This function blocks until new data is available for reading and the readyRead() signal has been emitted. The function will timeout after msecs milliseconds; the default timeout is 30000 milliseconds.

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

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

See also waitForBytesWritten().

[override virtual protected] qint64 QAbstractSocket::writeData(const char *data, qint64 size)

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

Автор Тема: Не происходит событие QAbstractSocket::SocketError  (Прочитано 11391 раз)
xaleva

Гость


Добрый день всем.Никак не могу поймать сигнал QAbstractSocket::SocketError.На одной из веток на этом форуме  http://www.prog.org.ru/topic_11560_0.html  нашел описание ситуации,подобной моей.Там все решалось при смене версии на 4.6,у меня это не помогает,вот отрывок кода:

    connect (_socket,SIGNAL (connected ()),this,SLOT (slotSocketConnected ()));
    connect (_socket,SIGNAL (readyRead ()),this,SLOT (slotSocketReadyRead ()));
    connect (_socket,SIGNAL (disconnected ()),this,SLOT (slotSocketDisconnected ()));
    connect (_socket,SIGNAL(error (QAbstractSocket::SocketError)),this,SLOT (slotSocketError (QAbstractSocket::SocketError)));
    _socket->connectToHost(ip,port,QIODevice::ReadWrite);
    _socket->waitForConnected (1000);

    if (_socket->state() == QAbstractSocket::UnconnectedState)
    {
        ……
    }

В документации есть такой вот момент  http://doc.crossplatform.ru/qt/4.3.2/qabstractsocket.html#error-2, попробывал прописать,все равно не помогло.Может кто-нибудь сталкивался с такой проблемой?


Записан
BRE

Гость


Если хочешь ловить сигналы, то откажись от _socket->waitForConnected (1000);

C++ (Qt)

void ClassName::createConnection( ... )
{
_socket = new QTcpSocket(...);
connect (_socket,SIGNAL (connected ()),this,SLOT (slotSocketConnected ()));
connect (_socket,SIGNAL (readyRead ()),this,SLOT (slotSocketReadyRead ()));
connect (_socket,SIGNAL (disconnected ()),this,SLOT (slotSocketDisconnected ()));
connect (_socket,SIGNAL(error (QAbstractSocket::SocketError)),this,SLOT (slotSocketError (QAbstractSocket::SocketError)));
_socket->connectToHost(ip,port,QIODevice::ReadWrite);
}
 

и по вызовам сигналов будешь определять, что происходит (подключились, пришли данные, произошла ошибка).

И QAbstractSocket::SocketError нужно зарегестрировать в мета-системе.

« Последнее редактирование: Январь 26, 2010, 12:04 от BRE »
Записан
xaleva

Гость


Сделал,теперь работает вроде,но при выдергивании шнура не срабатывает.А вообще должно ли?


Записан
Amigo_sa

Гость


Сделал,теперь работает вроде,но при выдергивании шнура не срабатывает.А вообще должно ли?

Я слышал, что в qt существует серьезные проблемы с возвращением ошибок связи. Проявляется, например, если во время http или ftp запроса выдернуть сетевой кабель. 1 мой знакомый писал троллям запрос по этому поводу и они обещали поправить к след. релизу.
Как вариант, в своем приложении я тупо делал таймер, который сбрасывается при любом сигнале dataTransferProgress или commandsDone. работает


Записан
xaleva

Гость


Так,щас заметил что слот срабатывает и при _socket->waitForConnected (1000);  ,когда сокет закрываю.
Однако при вытаскивании шнура события не происходит.А мне как раз нужно ловить это сообщение.Выдергивание шнура — думаю, самая распространенная трабла в моем случае

Вообще кто нить проверял,происходит ли какое нить событие типа дисконнект или один из ерроров когда plugged out ?

« Последнее редактирование: Январь 26, 2010, 13:13 от xaleva »
Записан
BRE

Гость


Вообще кто нить проверял,происходит ли какое нить событие типа дисконнект или один из ерроров когда plugged out ?

enum QAbstractSocket::SocketError:
QAbstractSocket::NetworkError   An error occurred with the network (e.g., the network cable was accidentally plugged out).

Но вот отслеживается ли это постоянно — не уверен.
Возможно, это состояние определяется при одном из действий типа connectToHost.


Записан
xaleva

Гость


Да,я как раз про эту ошибку и говорю.Я ее обрабатываю,но она не происходит при вытаскивании шнура.Кстати,у меня есть тоже такое подозрение,что произойдет при каком нить действии.Сейчас попробую


Записан
xaleva

Гость


Хм…чтот не     происходит…я уже и  state обрабатываю..все равно при анплагин никакого события не происходит


Записан
BRE

Гость


Хм…чтот не     происходит…я уже и  state обрабатываю..все равно при анплагин никакого события не происходит

Возможно, на некоторых платформах это работает, а на некоторых нет.
Попробуй погуглить на эту тему и воспользоваться сервисами предлагаемыми конкретной ОС.


Записан
Amigo_sa

Гость


Вообще кто нить проверял,происходит ли какое нить событие типа дисконнект или один из ерроров когда plugged out ?

Проверял для ftp=соединений. не происходит


Записан
xaleva

Гость


Да,телнетом тоже пока чтот не начнешь посылать,не почувствует.Складывается ощущение,что зависит все таки от ос..в данный момент сижу на слакваре


Записан
xaleva

Гость


Да,после проверки телнетом заметил что при выдергивании кабеля он не переходит в вайт…вообщем после недолгих изысканий нашел изначальные настройки в линухе

  # cat /proc/sys/net/ipv4/tcp_keepalive_time
  7200

  # cat /proc/sys/net/ipv4/tcp_keepalive_intvl
  75

  # cat /proc/sys/net/ipv4/tcp_keepalive_probes
  9
т.е 7200 сек кеепелайва)вощем проблема решена,всем спасибо Улыбающийся


Записан
xaleva

Гость


Для тех,кто наткнется на подобную траблу,замечу ,что проблема так просто не решается.Дело в том,что

net.ipv4.tcp_keepalive_time = 7200
Переменная определяет как часто следует проверять соединение, если оно
давно не используется. Значение переменной имеет смысл только для тех
сокетов, которые были созданы с флагом SO_KEEPALIVE.

После недолгих поисков находим способ установить SO_KEEPALIVE для моего сокета,а так же программно установить интервал tcp_keepalive_time

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>

….
// эти строки надо написать после того,как сокет перейдет в состояние конектед,потому как до этого setsockopt ругается на плохой дескриптор,что можно понять.
    int optval;
    socklen_t optlen = sizeof(optval);
    optval = 1;
    setsockopt(_socket->socketDescriptor(), SOL_SOCKET, TCP_KEEPIDLE, &optval, optlen);  // Это строкой я устанавливаю интервал tcp_keepalive_time  на 1 сек
    setsockopt(_socket->socketDescriptor(), SOL_SOCKET, SO_KEEPALIVE, &optval, optlen);  //  этой строкой врубаю SO_KEEPALIVE

Вот здесь можно найти подробное описание функции setsockopt и ее свойств http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.aix.commtechref/doc/commtrf2/setsockopt.htm

« Последнее редактирование: Январь 27, 2010, 10:44 от xaleva »
Записан
SABROG

Гость


Проблема давно решена уже. Зачем придумывать велосипед? Большинство протоколов реализуют команды типа PING/PONG.


Записан
xaleva

Гость


Можно по подробнее?


Записан

Nominate our 2022 Qt Champions!

This topic has been deleted. Only users with topic management privileges can see it.

  • Hi,
    I have a class which uses QTCPSocket. I create a tcp socket and connect the error signal to a slot in my class. All works fine, but no error() is emitted. The code is very simple, in the constructor I typed:

    m_socket = new QTcpSocket(this);
    connect(m_socket, &QTcpSocket::connected, this, &myTCPSocket::connected);
    connect(m_socket, &QTcpSocket::disconnected, this, &myTCPSocket::disconnected);
    connect(m_socket, &QTcpSocket::readyRead, this, &myTCPSocket::readyRead);
    connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(error(QAbstractSocket::SocketError)));
    

    and this is my error SLOT:

    void myTCPSocket::error(QAbstractSocket::SocketError socketError)
    {
        qDebug() << socketError;
    }
    

    I have never seen the error signal emitted. Is there something other to do?

  • It looks correct. If there is a problem with the signal-slot connection, you should check your debug output window, where Qt will report any problems.

    EDIT:
    Have you registered QAbstractSocket::SocketError as a metatype?

  • @kshegunov

    It looks correct. If there is a problem with the signal-slot connection, you should check your debug output window, where Qt will report any problems.
    

    I know what you’re talking about, but this time there are no warning in the debug window.

    Have you registered QAbstractSocket::SocketError as a metatype?
    

    mmm, this sounds new to me. Please, would you explain a but more? Why I should registed QAbstractSocket::SocketError? Isn’t it just an enum?

  • @Mark81
    Checkout in the documentation above the note. I could not believe it, but @kshegunov is right.

  • @koahnig
    Yeah, I see. I wonder why, though.
    Anyway, I added the following lines to my code:

    Q_DECLARE_METATYPE(QAbstractSocket::SocketError)
    qRegisterMetaType<QAbstractSocket::SocketError>("QAbstractSocket::SocketError");
    

    But it returns this error:

    error: a template declaration cannot appear at block scope
    

    So I moved the Q_DECLARE_METATYPE line outside the class. Now I get:

    redefinition of 'struct QMetaTypeId<QAbstractSocket::SocketError>'
    

    I’m reading the docs about Q_DECLARE_METATYPE, I’m sorry, but I cannot understand how to use it. I don’t see an example.
    Thank you

    EDIT:
    Another think I don’t understand. The docs says:

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

    but at the end of QAbstractSocket.h I see:

    Q_DECLARE_METATYPE(QAbstractSocket::SocketState)
    Q_DECLARE_METATYPE(QAbstractSocket::SocketError)
    

    So why I have to declare them another time?

  • I believe it goes like this:

    Q_DECLARE_METATYPE says that a type is recognized by the Qt type system but it doesn’t define the necessary code to do that. The necessary code has to be hooked into the Qt type system. Because the QtNetwork library is separate from the QtCore library, the QtCore library cannot define the necessary code because it would create a dependency on the QtNetwork library.

    So you have to register the code in your application if you want pass the types via signals and slots which is one important part of the Qt type system. Qt has to know how to pack and unpack types so that they can be marshaled and un-marshaled through the message queues.

    Even though the necessary registration could be done in the QtNetwork library in a library startup routine, I don’t think it is since the Qt networking classes can be used without signals and slots and an application doing that would not want all the Qt type system code pulled in.

  • @Mark81
    I had wondered about @kshegunov ‘s remark. Therefore, I looked it up and found the text section to my surprise.

    However, the «and» is wrong as far as I know, you should use either one but not both.
    qRegisterMetaType and Q_DECLARE_METATYPE .

    The other things is that you have mentioned that there has been no warning in a debug window, but you should see one when the type is not registered. Therefore, try again without registration and if there is a warning.
    Since you checked already the header file and a declaration is there, this is pointing towards a bug in documentation.

    And you are right another declaration shall not be required then.

    However, coming back top your initial problem. Just to be sure. Did you check with an error condition?

  • @Mark81
    Actually you’ll probably need only Q_DECLARE_METATYPE as this is done at compile time — exposing the type to the metatype system (I know it is an enum but it’s needed for the QVariant and the like). qRegisterMetaType you’ll need if creating objects by class name dynamically, and it seems for queued connections, generally you won’t need to call that function, but I suggest you do.

    @koahnig
    Directly from the documentation: «Adding a Q_DECLARE_METATYPE() makes the type known to all template based functions, including QVariant. Note that if you intend to use the type in queued signal and slot connections or in QObject’s property system, you also have to call qRegisterMetaType() since the names are resolved at runtime.»
    Sometimes you need both.

  • @koahnig
    It would be interesting to know when the Q_DECLARE_METATYPE lines at the bottom of QAbstractSocket.h were added. Perhaps the docs was not updated after that, so now it should look like: «QAbstractSocket::SocketError is a declared but not a registered metatype, so for queued connections, you will have to register it with qRegisterMetaType().»
    It’s weird no one else in the world has ever used this signal!

    Anyway, to test the error signal I’m simply trying to connect to my server (which works under normal conditions) with the Ethernet cable disconnected.

    I’m expecting at least one of the following errors:

    QAbstractSocket::ConnectionRefusedError	0	The connection was refused by the peer (or timed out).
    QAbstractSocket::HostNotFoundError	    2	The host address was not found.
    QAbstractSocket::SocketTimeoutError	    5	The socket operation timed out.
    QAbstractSocket::NetworkError	        7	An error occurred with the network (e.g., the network cable was accidentally plugged out).
    

    I also tried to connect before and then unplug the network cable. Nothing.

  • Oh dear! It works Even without qRegisterMetaType() — so the docs are definitely wrong.
    But it takes a huge time before fire, something about 30 s! This if I try to connect without the cable. After 30 seconds I get the NetworkError message.

    On the other hand, if I establish the connection and then I unplug the cable nothing happens, even after few minutes.
    Anyway I cannot wait for such a long time to inform the user the device is not connected anymore. I’m afraid I need to implement by myself a sort of software «ping» to be sure the remote device is still there. What a pity.

  • The default time out on QTcpSocket is 30s, you can reduce it if you want more responsive failure detection but you should be sure that you do not use a timeout less than normal round trip latency to the server.

    The docs are not wrong, you only need to register the types for Queued signal/slot connections as several have said above. Non-queued signal/slot connections are simply member function calls.

  • To add to @bsomervi there you have the default waiting time of 30 seconds

    @bsomervi said:

    The docs are not wrong, you only need to register the types for Queued signal/slot connections as several have said above. Non-queued signal/slot connections are simply member function calls.

    This is the first time I have seen such a difference for signal-slot connections. However, certainly I know only a small fraction of the documentation.
    If you say so, I assume that you are correct about different behaviour for queued and non-queued connections.
    The documentation is at least a bit ambiguous in that respect and the sentences might require a revision for clarity.

  • @koahnig said:

    This is the first time I have seen such a difference for signal-slot connections.

    It pops out every time you write a class that you intent to use as a signal/slot parameter in multithreaded application.

  • @kshegunov

    That there is a difference between queued and non-queued is clear.
    I had meant that there is difference in registered objects between queued and non-queued connections.
    I came across the need to register for my own classes. So far I thought that all Qt classes are registered alreay. Thought to have read a reference somewhere, but also quite a while ago.

  • @bsomervi

    The default time out on QTcpSocket is 30s, you can reduce it if you want more responsive failure detection
    

    English is not my primary language, thus I apologize if sometimes it’s hard to understand what I’m reading. Anyway I read through the docs and I cannot find how to reduce this timeout. As @koahnig said I could use the waitForConnected() function but: 1. the docs say it may fail randomly on Windows, 2. it blocks the execution of my code, 3. it could work only during connection, but it isn’t useful to detect a failure (i.e. the cable disconnected after).

    I cannot find a method like: setTimeout() or similar.

    Currently the only way I found is to periodically send back and forth a message: when I don’t receive the answer in few seconds I assume the connection is lost. I hate this approach, though! I’m pretty sure the system knows if a TCP socket isn’t alive anymore!

  • @Mark81 Sorry I have misled you, I was confusing the timeout on the wait…() functions with the asynchronous signals. You do not want the wait…() functions in the GUI thread as they block.

    The first thing to note is that normal TCP/IP will retry 12 times to send a data segment taking up to 9 minutes before it causes an error.

    I think you have two choices in the normal TCP/IP framework.

    If you are sending data and expecting a reply, you can start a single shot timer that is cancelled if the reply is received but causes your communications failed code to run when it times out.

    If you are just waiting for data then you will get no notification of errors as TCP/IP will wait forever on a disconnected circuit. So in this case you must have your server send you periodic «heartbeat» data to confirm its reachability.

Понравилась статья? Поделить с друзьями:
  • Qt platform plugin could be initialized ошибка как исправить
  • Q flash no disk drive found как исправить
  • Qt out of memory error opening database
  • Qt error processing project file
  • Pyzmq install error