Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt TCP/IP socket connection check

Tags:

tcp

sockets

qt

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.

like image 657
beparas Avatar asked Mar 06 '14 06:03

beparas


1 Answers

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.

like image 103
TheDarkKnight Avatar answered Nov 11 '22 09:11

TheDarkKnight