在 QTcpServer 的服务器端出现:远程主机关闭了连接

On server side in QTcpServer appears: The remote host closed the connection

我有一个 QTcpServer 应用程序和一个 QTcpClient 应用程序。 See my screenshot. 当客户端在与服务器交互后与服务器断开连接时,在服务器端出现事件(在客户端套接字中 - 在插槽中):

void CMyClient::onSocketDisplayError(QAbstractSocket::SocketError socketError)
{
    QString sErr = m_pClientSocket->errorString();
    m_pWin->AddMessageFormClient("Was gotten some error! " + sErr);
}

错误信息:

The remote host closed the connection.

之后出现一个事件:

void CMyClient::onSocketDisconnected()
{
    m_pWin->AddMessageFormClient("Client is disconnected!");
    m_pWin->UpdateDisconnectUI();
}

在服务器端生成 onSocketDisplayError 是否正确?

客户端断开连接的代码:

void MainWindow::on_pushButton_DisconnectFromServ_clicked()
{
    m_pSocket->disconnectFromHost();
    m_pSocket->waitForDisconnected(3000);
}

根据 QAbstractSocket 的文档,这是 QTcpSocket 后面的 class,因此您的客户端和服务器(强调我的):

To close the socket, call disconnectFromHost()QAbstractSocket enters QAbstractSocket::ClosingState. After all pending data has been written to the socket, QAbstractSocket actually closes the socket, enters QAbstractSocket::UnconnectedState, and emits disconnected(). If you want to abort a connection immediately, discarding all pending data, call abort() instead. If the remote host closes the connection, QAbstractSocket will emit error(QAbstractSocket::RemoteHostClosedError), during which the socket state will still be ConnectedState, and then the disconnected() signal will be emitted.

因此我会说:

  • disconnectFromHost是你应该用来关闭客户端或服务器
  • 服务器发出指示远程主机关闭连接的错误是正确的行为