#QT(TCP网络编程-客户端)

本文详细介绍了如何使用QTCreator创建一个简单的客户端UI界面,包括编写代码、连接服务器、数据通信以及部署设置。作者展示了如何在Qt中创建TCPsocket并实现客户端的基本功能。
摘要由CSDN通过智能技术生成

1.IDE:QTCreator


2.实验


3.记录

(1)做一个客户端UI界面(注意改标签名字,后面方便关联函数)

(2)编写客户端代码,代码编写完成之后,测试

a.cmd打开命令行

b.键入ipconfig,常看IPV4地址,然后同时打开客户端和服务端,将IPV4地址输入给客户端,然后端口选择一样即可,如果不行可以换其他端口试试

c.运行效果


4.代码

pro文件

QT       += core gui network

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++17

# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    main.cpp \
    widget.cpp

HEADERS += \
    widget.h

FORMS += \
    widget.ui

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QTcpsocket>
QT_BEGIN_NAMESPACE
namespace Ui {
class Widget;
}
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();
    QTcpSocket *tcpsocket;  //创建一个指针对象
private slots:
    void on_openclient_pb_clicked();
    void connected_slot();  //连接成功关联处理函数
    void readyRead_slot();  //准备读关联处理函数
    void on_closeclient_pb_clicked();

    void on_send_pb_clicked();

private:
    Ui::Widget *ui;
};
#endif // WIDGET_H

widget.cpp

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

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    tcpsocket=new QTcpSocket(this);
}

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

void Widget::on_openclient_pb_clicked()    //打开客户端按钮点击时处理函数
{
    tcpsocket->connectToHost(ui->ip_line->text(),ui->port_line->text().toUInt());   //连接指定ip地址的指定端口
    connect(tcpsocket,SIGNAL(connected()),this,SLOT(connected_slot()));   //关联连接成功处理函数
}

void Widget::connected_slot()
{
    connect(tcpsocket,SIGNAL(readyRead()),this,SLOT(readyRead_slot()));
}

void Widget::readyRead_slot()
{
    ui->receive_line->appendPlainText(tcpsocket->readAll());     //在接收区显示所有接收到的数据
}

void Widget::on_closeclient_pb_clicked()    //关闭客户端按钮按下处理函数
{
    tcpsocket->close();
}

void Widget::on_send_pb_clicked()     //发送按钮按下时处理函数
{
    tcpsocket->write(ui->send_line->text().toLocal8Bit().data());
}

  • 12
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值