QT TCP服务端判断客户端断开连接

一、客户端断开连接,disconnectFromHost函数可以实现;服务器判断客户端有没有断开连接,可以看有没有连接的客户端有没有返回错误

二、监听代码,主要实现监听任务连到本机,端口号为10086的客户端,并建连接信号与槽函数关系

void MainWindow::start_monitor()
{
    connect(&m_tcpServer,SIGNAL(newConnection()),this,SLOT(acceptConnection()));
    if(!m_tcpServer.listen(QHostAddress::Any,10086)){
        qDebug()<<m_tcpServer.errorString();
        close();
        return;
    }
     ui->textEdit->setText("监听");
}

三、新连接,有连接过来时,记录连接过来的对象,并建立收到数据和错误的槽函数

void MainWindow::acceptConnection()
{

    m_tcpServerConnection=m_tcpServer.nextPendingConnection();
    connect(m_tcpServerConnection,SIGNAL(readyRead()),this,SLOT(updateServerRead()));
    connect(m_tcpServerConnection, SIGNAL(error(QAbstractSocket::SocketError)),this, SLOT(MSGError(QAbstractSocket::SocketError)));
     ui->textEdit->setText("连接成功");
}

四、断开连接的处理

void MainWindow::MSGError(QAbstractSocket::SocketError)
{
    int error = m_tcpServerConnection->error();
    switch(error)
    {
        case QAbstractSocket::RemoteHostClosedError://客户端断开
        {
            QString hostAddress=m_tcpServerConnection->QAbstractSocket::peerAddress().toString();

            ui->textEdit->setPlainText(tr("客户端[%1]断开连接\r\n").arg(hostAddress));
            break;
        }
        default:
        {
            error = -1;
            QMessageBox::information(this, "show", m_tcpServerConnection->errorString());
            break;
        }
    }
}

五、客户端实现关闭

void MainWindow::btn_break_connect()
{
    m_tcpClient->disconnectFromHost();
    ui->plainTextEdit->appendPlainText("关闭连接");
}

六、相关的头文件部分

private:
    Ui::MainWindow *ui;

    QTcpServer m_tcpServer;
    QTcpSocket *m_tcpServerConnection;

public slots:
    void start_monitor();
    void acceptConnection();
    void updateServerRead();
    void MSGError(QAbstractSocket::SocketError);

你可能感兴趣的:(qt,vs2019)