问题描述
我正在编写 Qt TCP/IP 客户端.我想在将数据发送到服务器之前检查与服务器的连接状态.据我所知,我可以通过以下方法做到这一点
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
- 使用 bool 'ConnectionState',连接时设置此变量在 disconnected() 信号时切断并重置此变量.现在之前向服务器发送数据(client->write())检查 this 的值多变的.
- 使用这种client->state() == QTcpSocket::ConnectedState"方式来检查连接状态.
- Use a bool 'ConnectionState', set this variable when connected withsever and reset this variable on disconnected() signal. Now beforesending data to server (client->write()) check the value of thisvariable.
- use this 'client->state() == QTcpSocket::ConnectedState' way to check the connection state.
这是一个很好的做法.或任何其他方法.
Which is good practice. Or any other method to this.
提前致谢.
推荐答案
QTCPSocket
派生自 QAbstractSocket
,它提供了一个 state()
功能.这将返回以下枚举之一:-
QTCPSocket
is derived from QAbstractSocket
, which provides a state()
function. This returns one of the following enums: -
enum SocketState { UnconnectedState, HostLookupState, ConnectingState, ConnectedState, ..., ListeningState }
因此,假设 m_pSocket 是一个 QTcpSocket
,您只需执行此操作来检查它是否已连接:-
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.
这篇关于Qt TCP/IP 套接字连接检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!