Qtcpsocket signal error

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

Forum Updated on Feb 6th

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.

Содержание

  1. No such signal qtcpsocket error qabstractsocket socketerror
  2. QAbstractSocket Class
  3. Public Types
  4. Public Functions
  5. Reimplemented Public Functions
  6. Signals
  7. Protected Functions
  8. Reimplemented Protected Functions
  9. Detailed Description
  10. Member Type Documentation
  11. [since 5.0] enum QAbstractSocket:: BindFlag flags QAbstractSocket:: BindMode
  12. enum QAbstractSocket:: NetworkLayerProtocol
  13. [since 5.0] enum QAbstractSocket:: PauseMode flags QAbstractSocket:: PauseModes
  14. enum QAbstractSocket:: SocketError
  15. enum QAbstractSocket:: SocketOption
  16. enum QAbstractSocket:: SocketState
  17. enum QAbstractSocket:: SocketType
  18. Member Function Documentation
  19. QAbstractSocket:: QAbstractSocket ( QAbstractSocket::SocketType socketType, QObject *parent)
  20. [signal] void QAbstractSocket:: connected ()
  21. [signal] void QAbstractSocket:: disconnected ()
  22. [signal, since 5.15] void QAbstractSocket:: errorOccurred ( QAbstractSocket::SocketError socketError)
  23. [signal] void QAbstractSocket:: hostFound ()
  24. [signal] void QAbstractSocket:: proxyAuthenticationRequired (const QNetworkProxy &proxy, QAuthenticator *authenticator)
  25. [signal] void QAbstractSocket:: stateChanged ( QAbstractSocket::SocketState socketState)
  26. [virtual] QAbstractSocket::
  27. void QAbstractSocket:: abort ()
  28. [virtual, since 5.0] bool QAbstractSocket:: bind (const QHostAddress &address, quint16 port = 0, QAbstractSocket::BindMode mode = DefaultForPlatform)
  29. [since 6.2] bool QAbstractSocket:: bind ( QHostAddress::SpecialAddress addr, quint16 port = 0, QAbstractSocket::BindMode mode = DefaultForPlatform)
  30. [since 5.0] bool QAbstractSocket:: bind ( quint16 port = 0, QAbstractSocket::BindMode mode = DefaultForPlatform)
  31. [override virtual] qint64 QAbstractSocket:: bytesAvailable () const
  32. [override virtual] qint64 QAbstractSocket:: bytesToWrite () const
  33. [override virtual] void QAbstractSocket:: close ()
  34. [virtual] void QAbstractSocket:: connectToHost (const QString &hostName, quint16 port, QIODeviceBase::OpenMode openMode = ReadWrite, QAbstractSocket::NetworkLayerProtocol protocol = AnyIPProtocol)
  35. void QAbstractSocket:: connectToHost (const QHostAddress &address, quint16 port, QIODeviceBase::OpenMode openMode = ReadWrite)
  36. [virtual] void QAbstractSocket:: disconnectFromHost ()
  37. QAbstractSocket::SocketError QAbstractSocket:: error () const
  38. bool QAbstractSocket:: flush ()
  39. [override virtual] bool QAbstractSocket:: isSequential () const
  40. bool QAbstractSocket:: isValid () const
  41. QHostAddress QAbstractSocket:: localAddress () const
  42. quint16 QAbstractSocket:: localPort () const
  43. [since 5.0] QAbstractSocket::PauseModes QAbstractSocket:: pauseMode () const
  44. QHostAddress QAbstractSocket:: peerAddress () const
  45. QString QAbstractSocket:: peerName () const
  46. quint16 QAbstractSocket:: peerPort () const
  47. [since 5.13] QString QAbstractSocket:: protocolTag () const
  48. QNetworkProxy QAbstractSocket:: proxy () const
  49. qint64 QAbstractSocket:: readBufferSize () const
  50. [override virtual protected] qint64 QAbstractSocket:: readData ( char *data, qint64 maxSize)
  51. [override virtual protected] qint64 QAbstractSocket:: readLineData ( char *data, qint64 maxlen)
  52. [virtual, since 5.0] void QAbstractSocket:: resume ()
  53. [protected] void QAbstractSocket:: setLocalAddress (const QHostAddress &address)
  54. [protected] void QAbstractSocket:: setLocalPort ( quint16 port)
  55. [since 5.0] void QAbstractSocket:: setPauseMode ( QAbstractSocket::PauseModes pauseMode)
  56. [protected] void QAbstractSocket:: setPeerAddress (const QHostAddress &address)
  57. [protected] void QAbstractSocket:: setPeerName (const QString &name)
  58. [protected] void QAbstractSocket:: setPeerPort ( quint16 port)
  59. [since 5.13] void QAbstractSocket:: setProtocolTag (const QString &tag)
  60. void QAbstractSocket:: setProxy (const QNetworkProxy &networkProxy)
  61. [virtual] void QAbstractSocket:: setReadBufferSize ( qint64 size)
  62. [virtual] bool QAbstractSocket:: setSocketDescriptor ( qintptr socketDescriptor, QAbstractSocket::SocketState socketState = ConnectedState, QIODeviceBase::OpenMode openMode = ReadWrite)
  63. [protected] void QAbstractSocket:: setSocketError ( QAbstractSocket::SocketError socketError)
  64. [virtual] void QAbstractSocket:: setSocketOption ( QAbstractSocket::SocketOption option, const QVariant &value)
  65. [protected] void QAbstractSocket:: setSocketState ( QAbstractSocket::SocketState state)
  66. [override virtual protected] qint64 QAbstractSocket:: skipData ( qint64 maxSize)
  67. [virtual] qintptr QAbstractSocket:: socketDescriptor () const
  68. [virtual] QVariant QAbstractSocket:: socketOption ( QAbstractSocket::SocketOption option)
  69. QAbstractSocket::SocketType QAbstractSocket:: socketType () const
  70. QAbstractSocket::SocketState QAbstractSocket:: state () const
  71. [override virtual] bool QAbstractSocket:: waitForBytesWritten ( int msecs = 30000)
  72. [virtual] bool QAbstractSocket:: waitForConnected ( int msecs = 30000)
  73. [virtual] bool QAbstractSocket:: waitForDisconnected ( int msecs = 30000)
  74. [override virtual] bool QAbstractSocket:: waitForReadyRead ( int msecs = 30000)
  75. [override virtual protected] qint64 QAbstractSocket:: writeData (const char *data, qint64 size)

No such signal qtcpsocket error qabstractsocket socketerror

I am trying to handle non SSL requests with a QSSLSocket and send error message to the client. What I’m doing is this.

It works fine but every non-ssl request I do i get this warning :

«QSocketNotifier: Multiple socket notifiers for same socket 760 and type Read»

I think it’s because I have two sockets with the same socketDescriptor at the same time.

I read this in the QAbstractSocket doc :

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.

So I did the following :

But in there the socket is already closed.

What can I do ? Thanks !

@moffa13
Hello,
What you’re doing is very iffy. If I understand correctly what you want to accomplish, then call QSSLSocket:: ignoreSslErrors and then write to the unencrypted socket.
See the relevant documentation page.

Thanks for your reply.

The error thrown is QAbstractSocket::SslHandshakeFailedError (13) handled with the signal (error) and not with the signal (sslErrors) so I can’t handle it with ignoreSslErrors and event if I could what should I do ?

When you say «write to the unencrypted socket», I don’t know how to remove the encryption to write as plaintext because there is the startServerEncryption method but I thing there is no reverse function.

@moffa13
That’s why linked the documentation page. See what it says there:

If an error occurs, QSslSocket emits the sslErrors() signal. In this case, if no action is taken to ignore the error(s), the connection is dropped. To continue, despite the occurrence of an error, you can call ignoreSslErrors(), either from within this slot after the error occurs, or any time after construction of the QSslSocket and before the connection is attempted. This will allow QSslSocket to ignore the errors it encounters when establishing the identity of the peer. Ignoring errors during an SSL handshake should be used with caution, since a fundamental characteristic of secure connections is that they should be established with a successful handshake.

So as I see it, you connect the sslErrors signal to your slot, call ignoreSslErrors and after that use the socket as if it weren’t an SSL socket, but rather plain ol’ QTcpSocket .

I already did that; the problem is with my with slot because it’s not called.

So with this code

The error message is not written. Here’s my connect :

As I said only de error signal is called

What did I do wrong ?

@moffa13
Yeah, I’m talking nonsense. sslErrors() will not be emitted before the handshake has completed, which in your case it doesn’t. See instead QSslSocket::startClientEncryption and QSslSocket::startServerEncryption, which are specifically tailored for delayed handshakes.

I don’t really see how to do this

@moffa13
As far as understand it (I haven’t done this) you create your socket as usual. But instead of calling QSslSocket::connectToHostEncrypted , you call the regular connectToHost . And at one point, when you want to upgrade to an encrypted connection you call the QSslSocket::startClientEncryption . There are a few notes in the docs of how to do it for the server side too. However, I’m not that convinced that is what you want to do . am I misunderstand you?

Actually I am the server so I’m calling QSslSocket::startServerEncryption then the error is thrown. See the code:

Maybe I can do something with the slot(error) because at this point I can see the ssl error (handshake failed) and if I sleep the program the connection is closed yet. So, with this:

This is written «SSL error ! code : 13» and if I add _sleep(1000) the connection is not dropped yet so maybe I can do something with it.

@moffa13
If you get «SSL error ! code : 13» then you should also get the sslErrors() signal. You could try calling ignoreSslErrors() inside the error handler and this will hopefully prevent the socket from closing the connection.

Only the first works and the ignoreSslErrors() doesn’t change anything.

@moffa13
That is strange. I’m sorry I don’t know, I can’t see anything wrong with the snippets you provided. As far as I understand it, the signal should be raised (and you should get your slot executed).

I’m sending to you a short version my code, maybe you can try something ? If you want me to write it here, I’ll do it.

I currently have a very similar problem. I’m implementing a send mail client which should gracefully fall back to an unencrypted connection if encryption fails (and the user has decided to go ahead anyway). For that purpose I’ve connected to the QAbstractSocket::error() signal.

While I do get the signal it’s ultimately moot since the code in question (QSslSocketBackendPrivate::startHandshake() in qsslsocket_openssl.cpp) immediately closes the socket by calling QSslSocket::abort() after emitting the signal. Because of that calling QSslSocket::ignoreSslErrors() is never an option.

I currently have no workaround in place. Maybe the only solution is to connect to the disconnected() signal and then check whether the connection was closed because of a handshake error. If it was, then open a new unencrypted socket/connection. I’m open to suggestions, though. 🙂

Источник

QAbstractSocket Class

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

Note: All functions in this class are reentrant.

Public Types

Header: #include
CMake: find_package(Qt6 REQUIRED COMPONENTS Network)
target_link_libraries(mytarget PRIVATE Qt6::Network)
qmake: QT += network
Inherits: QIODevice
Inherited By:
enum BindFlag
flags BindMode
enum NetworkLayerProtocol
enum PauseMode
flags PauseModes
enum SocketError
enum SocketOption
enum SocketState
enum SocketType

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(QHostAddress::SpecialAddress addr, 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:

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

Member Type Documentation

[since 5.0] enum QAbstractSocket:: BindFlag
flags 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 success, your service is the only one that listens to the address and port. No services are allowed to rebind, even if they pass ReuseAddressHint. This option provides more security than ShareAddress, but on certain operating systems, it requires you to run the server with administrator privileges. On Unix and macOS, not sharing is the default behavior for binding an address and port, so this option is ignored. On Windows, this option uses the SO_EXCLUSIVEADDRUSE socket option.
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 . 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 IPv4
QAbstractSocket::IPv6Protocol 1 IPv6
QAbstractSocket::AnyIPProtocol 2 Either IPv4 or IPv6
QAbstractSocket::UnknownNetworkLayerProtocol -1 Other than IPv4 and IPv6

[since 5.0] enum QAbstractSocket:: PauseMode
flags 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

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

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

enum QAbstractSocket:: SocketState

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

Constant Value Description
QAbstractSocket::UnconnectedState 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.

enum QAbstractSocket:: SocketType

This enum describes the transport layer protocol.

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

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.

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

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

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

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

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

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

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

[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 6.2] bool QAbstractSocket:: bind ( QHostAddress::SpecialAddress addr, quint16 port = 0, QAbstractSocket::BindMode mode = DefaultForPlatform)

This is an overloaded function.

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

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

This function was introduced in Qt 6.2.

[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

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

[override virtual] qint64 QAbstractSocket:: 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.

[override virtual] void QAbstractSocket:: 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.

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

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.

QAbstractSocket::SocketError QAbstractSocket:: error () const

Returns the type of error that last occurred.

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.

[override virtual] bool QAbstractSocket:: 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.

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.

quint16 QAbstractSocket:: localPort () const

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

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

Returns the pause mode of this socket.

This function was introduced in Qt 5.0.

QHostAddress QAbstractSocket:: peerAddress () const

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

QString QAbstractSocket:: peerName () const

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

quint16 QAbstractSocket:: peerPort () const

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

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

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.

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.

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

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

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

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

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

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

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

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

void QAbstractSocket:: setProxy (const QNetworkProxy &networkProxy)

Sets the explicit network proxy for this socket to networkProxy.

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

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

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

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

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

Sets the type of error that last occurred to socketError.

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

Sets the given option to the value described by value.

Note: Since the options are set on an internal socket the options only apply if the socket has been created. This is only guaranteed to have happened after a call to bind(), or when connected() has been emitted.

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

Sets the state of the socket to state.

[override virtual protected] qint64 QAbstractSocket:: 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.

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

Returns the value of the option option.

QAbstractSocket::SocketType QAbstractSocket:: socketType () const

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

QAbstractSocket::SocketState QAbstractSocket:: state () const

Returns the state of the socket.

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

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.

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

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.

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

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.

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

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.

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

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

В© 2023 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.

Источник

  • Home
  • Forum
  • Qt
  • Qt Programming
  • problem in QAbstractSocket::SocketError

  1. 11th March 2011, 15:55


    #1

    Default problem in QAbstractSocket::SocketError

    Hi everyone,
    I am using qt 4.6.2. I am trying to use socket error for unplugging the network cable.I am using connect function to get the error.But when i removed the cable no error is occurring .

    1. switch(err)

    2. {

    3. case 0:QMessageBox::critical(0,"connection error","The connection was refused by the peer (or timed out).",QMessageBox::Ok);

    4. break;

    5. case 2:QMessageBox::critical(0,"connection error","The host address was not found.",QMessageBox::Ok);

    6. break;

    7. break;

    8. break;

    9. qDebug()<<"error is ......."<<err;

    10. break;

    11. }

    To copy to clipboard, switch view to plain text mode 

    Is there anything to do more ?


  2. 11th March 2011, 16:00


    #2

    Default Re: problem in QAbstractSocket::SocketError

    After remove network cable do you use any socket function?

    I think if remove cable you receive stateChanged or disconnected signal. And receive error only if you do any socket operation after cable removing.

    Try read Qt documentation before ask stupid question.


  3. 11th March 2011, 16:31


    #3

    Default Re: problem in QAbstractSocket::SocketError

    I have function for stateChanged and disconnected signal.But when i removed the cable no one is called.


  4. 11th March 2011, 16:34


    #4

    Default Re: problem in QAbstractSocket::SocketError

    ok. i try code and will tell later. But say me plz, what class is clt ?

    And your OS plz.

    Last edited by unit; 11th March 2011 at 17:02.

    Try read Qt documentation before ask stupid question.


  5. 11th March 2011, 20:48


    #5

    Default Re: problem in QAbstractSocket::SocketError

    .h

    1. #ifndef MAINWINDOW_H

    2. #define MAINWINDOW_H

    3. #include <QMainWindow>

    4. #include <QTcpSocket>

    5. #include <QDateTime>

    6. namespace Ui {

    7. class MainWindow;

    8. }

    9. {

    10. Q_OBJECT

    11. public:

    12. explicit MainWindow(QWidget *parent = 0);

    13. ~MainWindow();

    14. private:

    15. private slots:

    16. void on_pushButton_clicked();

    17. void st_connected();

    18. void st_disconnected();

    19. void on_pushButton_2_clicked();

    20. private:

    21. Ui::MainWindow *ui;

    22. };

    23. #endif // MAINWINDOW_H

    To copy to clipboard, switch view to plain text mode 

    .cpp

    1. #include "mainwindow.h"

    2. #include "ui_mainwindow.h"

    3. MainWindow::MainWindow(QWidget *parent) :

    4. ui(new Ui::MainWindow)

    5. {

    6. ui->setupUi(this);

    7. connect(socket,SIGNAL(connected()),this,SLOT(st_connected()));

    8. connect(socket,SIGNAL(disconnected()),this,SLOT(st_disconnected()));

    9. connect(socket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),this,SLOT(st_stateChange(QAbstractSocket::SocketState)));

    10. }

    11. MainWindow::~MainWindow()

    12. {

    13. delete ui;

    14. delete socket;

    15. }

    16. void MainWindow::on_pushButton_clicked()

    17. {

    18. socket->connectToHost("adsl.by", 80);

    19. }

    20. void MainWindow::st_connected()

    21. {

    22. ui->textEdit->append("Connected at " + QDateTime::currentDateTime().toString("hh:mm:ss dd.MM.yyyy"));

    23. }

    24. void MainWindow::st_disconnected()

    25. {

    26. ui->textEdit->append("Disconnected at " + QDateTime::currentDateTime().toString("hh:mm:ss dd.MM.yyyy"));

    27. }

    28. void MainWindow::st_error(QAbstractSocket::SocketError socketError)

    29. {

    30. ui->textEdit->append("Error " + socket->errorString() + " at " + QDateTime::currentDateTime().toString("hh:mm:ss dd.MM.yyyy"));

    31. }

    32. void MainWindow::st_stateChange(QAbstractSocket::SocketState socketState)

    33. {

    34. ui->textEdit->append("State change to " + statetoString(socketState) + " at " + QDateTime::currentDateTime().toString("hh:mm:ss dd.MM.yyyy"));

    35. }

    36. void MainWindow::on_pushButton_2_clicked()

    37. {

    38. if(socket->isOpen())

    39. socket->disconnectFromHost();

    40. }

    41. {

    42. switch(socketState)

    43. {

    44. case QAbstractSocket::UnconnectedState : statestring="the socket is not connected";

    45. break;

    46. case QAbstractSocket::HostLookupState : statestring="the socket is performing a host name lookup";

    47. break;

    48. case QAbstractSocket::ConnectingState : statestring="the socket has started establishing a connection";

    49. break;

    50. case QAbstractSocket::ConnectedState : statestring="a connection is established";

    51. break;

    52. case QAbstractSocket::BoundState : statestring="the socket is bound to an address and port";

    53. break;

    54. case QAbstractSocket::ClosingState : statestring="the socket is about to close";

    55. break;

    56. case QAbstractSocket::ListeningState : statestring="listening state";

    57. break;

    58. default: statestring="unknown state";

    59. }

    60. return statestring;

    61. }

    To copy to clipboard, switch view to plain text mode 

    i’m coded and have next result when remove cable after connect button clicked

    1. State change to the socket is performing a host name lookup at 21:42:39 11.03.2011

    2. State change to the socket has started establishing a connection at 21:42:40 11.03.2011

    3. State change to a connection is established at 21:42:40 11.03.2011

    4. Connected at 21:42:40 11.03.2011

    5. Error The remote host closed the connection at 21:42:51 11.03.2011

    6. State change to the socket is about to close at 21:42:51 11.03.2011

    7. State change to the socket is not connected at 21:42:51 11.03.2011

    8. Disconnected at 21:42:51 11.03.2011

    To copy to clipboard, switch view to plain text mode 

    Last edited by unit; 11th March 2011 at 21:52.

    Try read Qt documentation before ask stupid question.


  6. 12th March 2011, 07:34


    #6

    Default Re: problem in QAbstractSocket::SocketError

    Thanks for reply .But the above code is not working for me when i removed the cable.
    I am using fedora 11 (64bit linux kernel 2.6.29) .The clt is a object of client class which inherits QTcpSocket class.


  7. 12th March 2011, 10:01


    #7

    Default Re: problem in QAbstractSocket::SocketError

    Maybe it’s platform specific or network card driver problem.

    If you want known interface state try use QNetworkConfiguration

    Try read Qt documentation before ask stupid question.


  8. 12th March 2011, 15:34


    #8

    Default Re: problem in QAbstractSocket::SocketError

    Quote Originally Posted by sattu
    View Post

    Hi everyone,
    I am using qt 4.6.2. I am trying to use socket error for unplugging the network cable.I am using connect function to get the error.But when i removed the cable no error is occurring .
    Is there anything to do more ?

    http://doc.trolltech.com/latest/qnet….html#isOnline


  9. 14th March 2011, 05:56


    #9

    Default Re: problem in QAbstractSocket::SocketError

    QNetworkConfigurationManager class was introduced in Qt 4.7.But i am using 4.6.2.So how can i add this class in my qt application ?


  10. 14th March 2011, 10:24


    #10

    Default Re: problem in QAbstractSocket::SocketError

    Try read Qt documentation before ask stupid question.


  11. 16th March 2011, 07:12


    #11

    Default Re: problem in QAbstractSocket::SocketError

    I tried the program in qt 4.7 (os xp2) and it is working fine.I think there is some problem in qt4.6.2
    thanks


Similar Threads

  1. Replies: 1

    Last Post: 8th October 2010, 13:21

  2. Replies: 0

    Last Post: 17th March 2010, 16:55

  3. Replies: 4

    Last Post: 25th January 2009, 06:40

  4. Replies: 1

    Last Post: 25th February 2008, 11:36

  5. Replies: 1

    Last Post: 24th February 2008, 18:05

Bookmarks

Bookmarks


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules

Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.

Понравилась статья? Поделить с друзьями:
  • Qt5webenginewidgets dll как исправить ошибку
  • Qg18de ошибка 0340
  • Qt5core dll error
  • Qg18de ошибка 0335
  • Qt5 collect2 error ld returned 1 exit status