Bootstrap

Qt 网络编程制作一个客户端与服务器

tcp服务器

使用 QtcpServer 与 QtcpSocket 类

使用QtcpServer、QtcpSocket类之前在项目的.pro文件中

添加 Qt += network

步骤
  1. 初始化一个QTcpServer 对象,注意初始化时传入一个this指针
QTcpServer *tcpServer = new QTcpServer(this);
  1. 关联newConnection信号,开启监听后,当一个新的连接接入,会发射newConnection信号,并使用关联的newConnection_slot槽函数处理。
connect(tcpServer, &QTcpServer::newConnection, this, &TcpServer::newConnection_slot);
  1. 定义newConnection_slot槽函数
void TcpServer::newConnection_slot()
{
    // 使用 QTcpServer的nextPendingConnection方法获取接入的QTcpSocket对象
    QTcpSocket* tcpSocket = tcpServer->nextPendingConnection();    
    // 使用QTcpSocket类的peerAddress和peerPort方法获取客户端ip地址和端口号
    QString socketName = QString("%1:%2").arg(tcpSocket->peerAddress().toString()).arg(tcpSocket->peerPort());  
    // tcpClients是一个QMap<QPair<QString, QTcpSocket *>> 类型的关联容器,用于存储当前接入的tcp连接
    if (!tcpClients.contains(socketName)) tcpClients.insert(socketName, tcpSocket);

    showMsg(QString("connect %1:%2").arg(tcpSocket->peerAddress().toString())
            .arg(tcpSocket->peerPort()));

    // 下拉框添加数据
    ui->selectSocketCb->addItem(socketName);
    // 关联tcpSocket的readyRead和disconnected信号分别用对应的readyRead_slot、disconnected_slot槽函数处理
    connect(tcpSocket, &QTcpSocket::readyRead, this, &TcpServer::readyRead_slot);
    connect(tcpSocket, &QTcpSocket::disconnected, this, &TcpServer::disconnected_slot);
}
  1. 定义readyRead_slot槽函数
void TcpServer::readyRead_slot()
{
    // 使用QObject::sender()获取当前发射信号的QTcpSocket对象
    QTcpSocket* tcpSocket = (QTcpSocket *)QObject::sender();
    QString buf;
    // 发送的数据使用QString类的 toLocal8Bit方法转换为unicode编码(于此对应toLatin1转换为ASCII编码),这里使用QTextCodec::codecForName("GB2312")->toUnicode()方法
    buf = QTextCodec::codecForName("GB2312")->toUnicode(tcpSocket->readAll());
    qDebug() << "recv " << buf;

    showMsg(QString("%1-> %2").arg(tcpSocket->localAddress().toIPv4Address()).arg(buf));
}
  1. 定义disconnected_slot槽函数
void TcpServer::disconnected_slot()
{
    QTcpSocket* tcpSocket = (QTcpSocket *)QObject::sender();
    QString socketName = QString("%1:%2").arg(tcpSocket->peerAddress().toString()).arg(tcpSocket->peerPort());

    tcpClients.remove(socketName);

//    qDebug() << "关闭";
    int index = ui->selectSocketCb->findText(socketName);
    if (index != -1) ui->selectSocketCb->removeItem(index);
    tcpSocket->deleteLater();

    showMsg(QString("%1 已断开连接").arg(socketName));

}
  1. 开启监听
void TcpServer::on_startBtn_clicked()
{
    if (ui->portEdit->text().isEmpty())
    {
        QMessageBox::warning(this, "警告", "端口号不能为空!", "确定");
        return ;
    }
    if (!tcpServer->isListening())
    {
        if (tcpServer->listen(QHostAddress::Any, ui->portEdit->text().toUInt()))
        {
            showMsg(QString("服务器已开启 %1 port %2").arg(tcpServer->serverAddress().toString()).arg(tcpServer->serverPort()));

        } else {
            showMsg("服务器开启失败: "+tcpServer->errorString());
        }

        ui->startBtn->setEnabled(false);
        ui->stopBtn->setEnabled(true);
    }

}
tcp客户端
// 初始化QTcpSocket实例
QTcpSocket *tcpSocket = new QTcpSocket(this);
// 中断所有连接
tcpSocket->abort();
// 关联connected信号
connect(tcpSocket, &QTcpSocket::connected, this, &TcpClient::connection_slot);
// 关联 readyRead信号
connect(tcpSocket, &QTcpSocket::readyRead, this, &TcpClient::readyRead_slot);
// 连接到HOST
quint16 port = ui->portEdit->text().toUInt();
QString ip = ui->ipEdit->text();
tcpSocket->connectToHost(ip, port);
if (tcpSocket->waitForConnected(1000))
{
    showMsg("连接成功!");
    ui->closeBtn->setEnabled(true);
    ui->openBtn->setEnabled(false);
    ui->sendBtn->setEnabled(true);
} else {
    showMsg("连接失败!");
}


connection_slot
void TcpClient::connection_slot()
{
    showMsg(QString("连接服务器 %1:%2").arg(tcpSocket->peerAddress().toString())
            .arg(tcpSocket->peerPort()));

}
readyRead_slot
void TcpClient::readyRead_slot()
{
    QString buf = QTextCodec::codecForName("GB2312")->toUnicode(tcpSocket->readAll());
    qDebug() << "recv " << buf;
    showMsg(buf);
}
发送数据
void TcpClient::on_sendBtn_clicked()
{
    QString buf = ui->sendEdit->text();
    if (buf.isEmpty())
    {
        QMessageBox::warning(this, "警告", "发送内容不能为空!", "确定");
        return ;
    }

    qDebug() << "send msg " << buf;

    tcpSocket->write(buf.toLocal8Bit().data());
    ui->sendEdit->clear();

}