在用QT写服务端时想要知道客户端是否断开连接,百度一下没有找到方法,看了下帮助文档,得到以下方法,实测可用,如有更好的还请告知
- enum SocketError {
- ConnectionRefusedError,
- RemoteHostClosedError,//客户端断开时出现这个错误
- HostNotFoundError,
- SocketAccessError,
- SocketResourceError,
- SocketTimeoutError, /* 5 */
- DatagramTooLargeError,
- NetworkError,
- AddressInUseError,
- SocketAddressNotAvailableError,
- UnsupportedSocketOperationError, /* 10 */
- UnfinishedSocketOperationError,
- ProxyAuthenticationRequiredError,
- SslHandshakeFailedError,
- ProxyConnectionRefusedError,
- ProxyConnectionClosedError, /* 15 */
- ProxyConnectionTimeoutError,
- ProxyNotFoundError,
- ProxyProtocolError,
- OperationError,
- SslInternalError, /* 20 */
- SslInvalidUserDataError,
- TemporaryError,
- UnknownSocketError = -1
- };
远程主机关闭连接,注解:client socket 将送出通知后关闭
QAbstractSocket::error() const
Returns the type of error that last occurred.
返回最后出现的错误类型
下面为实现代码
connect(serverConnect, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(MSGError(QAbstractSocket::SocketError)));//建立槽函数,获取错误信息
void DataDisplay::MSGError(QAbstractSocket::SocketError)
{
error = serverConnect->error();
switch(error)
{
case QAbstractSocket::RemoteHostClosedError://客户端断开
{
QString hostAddress=serverConnect->QAbstractSocket::peerAddress().toString();
ui->m_display->insertPlainText(tr("客户端[%1]断开连接\r\n").arg(hostAddress));
break;
}
default:
{
error = -1;
QMessageBox::information(this, "show", serverConnect->errorString());
break;
}
}
}