目录
一.widget.ui界面设计
拖拽左侧Label控件到页面中,分别显示Label:客户端;Label:服务器;Label:服务器窗口号。
拖拽左侧Push Button控件到页面中,分别为: 连接,取消,两个按钮。在右侧将其objectName 分别设置为 ;"connectButton" ; "cancelButton" 。
拖拽左侧Line Edit控件到页面中,在右侧将其objectName 设置为"ipLineEdit"和"portlineEdit",目的是输入服务器地址和服务器端口号。
二.创建TCP通信
1.pro文件添加network模块。
2.添加对应头文件
#include <QTcpSocket>:QTcpSocket 是 Qt Network 模块的一部分,它提供了一个 TCP(Transmission Control Protocol)客户端和服务器的接口,用于在应用程序中进行网络通信,如创建套接字、发送和接收数据、处理连接和断开等。
#include <QHostAddress>:QHostAddress 类是 Qt Network 模块中的一个类,用于表示 IP 地址和主机名。它提供了一种方便的方式来处理 IP 地址,支持 IPv4 和 IPv6 地址。
#include <QMessageBox>:QMessageBox 类是 Qt Widgets 模块中的一个类,用于显示消息框和对话框,以便与用户进行交互。使用 QMessageBox 类来创建和显示各种类型的消息框,例如提示框、警告框、错误框等。
3.定义槽函数,即与 UI 中的按钮点击事件相关联的函数
on_connectButton_clicked()
:当连接按钮被点击时调用。on_cancelButton_clicked()
:当取消按钮被点击时调用。
onConnected()
:当与服务器连接成功时调用。onDisconnected()
:当与服务器断开连接时调用。
4.定义类的私有成员
QTcpSocket *socket;
:一个QTcpSocket
对象,用于网络通信。QWidget* m_this;
:一个指向自身的指针,用于在槽函数中作为this
使用。
5.创建socket对象
6.取消连接
7.连接![](https://img-blog.csdnimg.cn/direct/b53adf17ed1048b3b9e18f863cabb187.png)
8.连接成功
9.连接失败
10.效果图
三.代码演示
1.h文件
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTcpSocket>
#include <QHostAddress> //IP
#include <QDebug>
#include <QMessageBox>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void on_connectButton_clicked();
void on_cancelButton_clicked();
void onConnected();
void onDisconnected();
private:
Ui::Widget *ui;
QTcpSocket *socket;
QWidget* m_this;
};
#endif // WIDGET_H
2.cpp文件
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
socket = new QTcpSocket; //创建socket对象
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_cancelButton_clicked()
{
this->close();
}
void Widget::onConnected()
{
QMessageBox::information(this,"连接提示","连接成功");
}
void Widget::onDisconnected()
{
QMessageBox::warning(this,"连接提示","连接失败,网络断开");
}
void Widget::on_connectButton_clicked()
{
//获取ip地址和端口号
QString IP = ui->ipLineEdit->text();
QString port = ui->portlineEdit->text();
qDebug() << IP;
qDebug() << port;
m_this=this;
//连接服务器
socket->connectToHost(QHostAddress(IP),port.toShort());
//连接服务器成功,socket对象发出信号
connect(socket,&QTcpSocket::connected,this,&Widget::onConnected);
//连接断开,socket会发出信号
connect(socket,&QTcpSocket::disconnected,this,&Widget::onDisconnected);
}