Qt网络编程专栏

  • 服务器端TCP通信有两个套接字,一个是监听的(QTcpServer),一个是建立好连接通信的(QTcpSocket),而客户端只有一个。

  • bind绑定可以理解为固定一个端口

  • 常规TCP通讯和QtTCP通讯的区别

Qt网络编程专栏
Qt网络编程专栏

  • 服务器代码示例:

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QTcpServer>//监听套接字
#include <QTcpSocket>//通信套接字
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();

private slots:
    void on_buttonSend_clicked();

    void on_buttonClose_clicked();

private:
    Ui::Widget *ui;
    QTcpServer *tcpServer;//监听套接字;
    QTcpSocket *tcpSocket;//通信套接字
};
#endif // WIDGET_H
#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    tcpServer = NULL;
    tcpSocket = NULL;//防止点击按钮出现野指针
    //监听套接字
    tcpServer = new QTcpServer(this);//指定父对象的唯一作用就是可以自动回收空间,不指定也没关系
    tcpServer->listen(QHostAddress::Any,8888);//参数1的宏绑定当前网口所有的ip地址,参数二是端口
    setWindowTitle("服务器,8888");
    connect(tcpServer,&QTcpServer::newConnection,
            [=](){
            //取出建立好连接的套接字
        tcpSocket = tcpServer->nextPendingConnection();
            //获取对方的IP和端口
        QString ip = tcpSocket->peerAddress().toString();
        qint16 port = tcpSocket->peerPort();
        QString temp = QString("[%1:%2]:成功连接").arg(ip).arg(port);   //temp代表的是临时的意思 拼接字符串常用方法
        ui->textEditRead->setText(temp);
        connect(tcpSocket,&QTcpSocket::readyRead,          //当有数据可读时就进来
                [=]()
        {
            //从通信套接字中取出内容
           QByteArray array =  tcpSocket->readAll();
           ui->textEditRead->append(array);
        }
                );
    }
            );

}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_buttonSend_clicked()
{
    if(tcpSocket == NULL)
    {
        return;
    }
    //获取编辑区内容
    QString str = ui->textEditWrite->toPlainText();

    //只要往刚取出的套接字里面写东西,系统就自动发到客户端
    tcpSocket->write(str.toUtf8().data());//toUtf8()是防止有中文
}

void Widget::on_buttonClose_clicked()
{
    if(tcpSocket == NULL)
    {
        return;
    }
    //主动和客户端断开连接
    tcpSocket->disconnectFromHost();
    tcpSocket->close();
    tcpSocket = NULL;
}

  • 客户端代码示例:

#ifndef CLIENTWIDGET_H
#define CLIENTWIDGET_H

#include <QWidget>
#include <QTcpSocket>


namespace Ui {
class ClientWidget;
}

class ClientWidget : public QWidget
{
    Q_OBJECT

public:
    explicit ClientWidget(QWidget *parent = nullptr);
    ~ClientWidget();

private slots:
    void on_buttonConnect_clicked();

    void on_buttonSend_clicked();

    void on_buttonClose_clicked();

private:
    Ui::ClientWidget *ui;
    QTcpSocket *tcpSocket;
};

#endif // CLIENTWIDGET_H

#include "clientwidget.h"
#include "ui_clientwidget.h"
#include <QHostAddress>
ClientWidget::ClientWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ClientWidget)
{
    ui->setupUi(this);
    tcpSocket = NULL;
    tcpSocket = new QTcpSocket(this);
    connect(tcpSocket,&QTcpSocket::connected,
            [=](){
        ui->textEditRead->setText("成功和服务器建立连接");
    }
            );
    connect(tcpSocket,&QTcpSocket::readyRead,
            [=](){
        //获取对方发送的内容
        QByteArray array = tcpSocket->readAll();
        ui->textEditRead->append(array);
    }
            );
}

ClientWidget::~ClientWidget()
{
    delete ui;
}

void ClientWidget::on_buttonConnect_clicked()
{
    //获取服务器IP端口
    QString ip = ui->lineEditIP->text();
    qint16 port = ui->lineEditPort->text().toInt();
    //主动和服务器建立连接
    tcpSocket->connectToHost(QHostAddress(ip),port);
}

void ClientWidget::on_buttonSend_clicked()
{
    //获取编辑框内容
    QString str = ui->textEditWrite->toPlainText();
    //发送数据
    tcpSocket->write(str.toUtf8().data());

}

void ClientWidget::on_buttonClose_clicked()
{
    //主动和对方断开连接
    tcpSocket->disconnectFromHost();
    tcpSocket->close();
}

上一篇:Qt Designer中QAbstractButton派生按钮部件autoRepeat、autoRepeatDelay、autoRepeatInterval属性


下一篇:我以订披萨为例,给女朋友详细讲了Java设计模式的3种工厂模式