TOP

49.Qt-网络编程之QTCPSocket和QTCPServer(实现简易网络调试助手)(三)
2019-08-14 00:08:38 】 浏览:193
Tags:49.Qt- 网络编程 QTCPSocket QTCPServer 实现 简易 网络 调试 助手

t *>(); foreach (QTcpSocket *tcp, m_tcps) { tcp->write(ui->sendEdit->toPlainText().toLocal8Bit(),ui->sendEdit->toPlainText().toLocal8Bit().length()); } } } } } Widget::~Widget() { QList<QTcpSocket *> m_tcps = m_server.findChildren<QTcpSocket *>(); foreach (QTcpSocket *tcp, m_tcps) { tcp->close(); } if(m_client.isOpen()) { m_client.close(); qDebug()<<"m_client close"; } delete ui; }

5.3 clentHandler.cpp介绍

该cpp主要用来处理客户端操作相关的文件.

#include "widget.h"
#include "ui_widget.h"

void Widget::initClientSignals()  //初始化客户端信号槽
{
    connect(&m_client, SIGNAL(connected()), this, SLOT(onClientConnected()));
    connect(&m_client, SIGNAL(disconnected()), this, SLOT(onClientDisconnected()));
    connect(&m_client, SIGNAL(readyRead()), this, SLOT(onClientDataReady()));
    connect(&m_client, SIGNAL(bytesWritten(qint64)), this, SLOT(onClientBytesWritten(qint64)));
    connect(&m_client, SIGNAL(error(QAbstractSocket::SocketError )), this, SLOT(onClientErr(QAbstractSocket::SocketError)));
}
bool Widget::startClient()         //启动客户端
{
    QString ip = QString("%1.%2.%3.%4").arg(ui->ipAddr1->text()).arg(ui->ipAddr2->text()).arg(ui->ipAddr3->text()).arg(ui->ipAddr4->text());
    qDebug()<<ip;
    m_client.connectToHost(ip, ui->ipPort->text().toInt());
    if(m_client.waitForConnected(800))
    {
        return true;
    }
    else
    {
        QMessageBox::information(this,"提示",QString("连接超时"),QMessageBox::Ok);
        return false;
    }
}

void Widget::onClientConnected()
{
    startConnect(true);
    QMessageBox::information(this,"提示","连接成功",QMessageBox::Ok);
    ui->localPort->setText(QString("%1").arg(m_client.localPort())); //显示本地端口号
}
void Widget::onClientDisconnected()
{
    startConnect(false);
    QMessageBox::information(this,"提示","断开完成",QMessageBox::Ok);
}
void Widget::onClientDataReady()
{
    if(m_client.peerAddress().toString()!=targetAddr || m_client.peerPort()!=targetPort  )
    {
        targetAddr = m_client.peerAddress().toString();
        targetPort = m_client.peerPort();
        ui->recvEdit->insertPlainText("[接受来自"+ targetAddr+":"+QString("%1").arg(targetPort)+"]:\r\n");
    }
    ui->recvEdit->moveCursor(QTextCursor::End);
    ui->recvEdit->insertPlainText(QString::fromLocal8Bit(m_client.readAll())+"\r\n");
}
void Widget::onClientBytesWritten(qint64 bytes)
{
    qDebug() << "onBytesWritten:" << bytes;
    ui->sendLenLabel->setText(QString("%1").arg(ui->sendLenLabel->text().toInt()+bytes));
}

void  Widget::onClientErr(QAbstractSocket::SocketError socketError)
{
    qDebug()<<"onClientErr:"<<socketError;
    m_client.close();
    startConnect(false);
    QMessageBox::information(this,"提示",QString("连接失败:%1").arg((int)socketError),QMessageBox::Ok);
}

5.4 serverHandler.cpp介绍

该cpp主要用来处理服务器操作相关的文件

首页 上一页 1 2 3 4 下一页 尾页 3/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Qt开源编辑器qsciscintilla的一些.. 下一篇正睿暑期培训day4考试