Search code examples
qtsocketstcp

Qt TCP/IP socket connection check


I am writing Qt TCP/IP client. I want to check the connection state with server before send data to sever. As far my knowledge I can do this by following methods

  • Use a bool 'ConnectionState', set this variable when connected with sever and reset this variable on disconnected() signal. Now before sending data to server (client->write()) check the value of this variable.
  • use this 'client->state() == QTcpSocket::ConnectedState' way to check the connection state.

Which is good practice. Or any other method to this.

Thanks In advance.


Solution

  • QTCPSocket is derived from QAbstractSocket, which provides a state() function. This returns one of the following enums: -

    enum SocketState { UnconnectedState, HostLookupState, ConnectingState, ConnectedState, ..., ListeningState }
    

    So, assuming m_pSocket is a QTcpSocket, you would simply do this to check if it is connected:-

    bool connected = (m_pSocket->state() == QTcpSocket::ConnectedState);
    

    You could add a boolean and keep track of the state, but if a network error occurs you need to ensure that it is always in-sync with the actual connection state.