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
Which is good practice. Or any other method to this.
Thanks In advance.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With