#QT(TCP网络编程-服务端)

本文介绍了如何在QTCreator中创建一个简单的TCP服务端,包括界面设计、服务器代码编写(包括信号槽连接和功能处理)、以及部署配置。
摘要由CSDN通过智能技术生成

1.IDE:QTCreator


2.实验:编写一个tcp服务端

QTcpsever

QTcpsocket


3.记录:

(1)先搭建界面

(2)服务端代码

a.           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

b.               widget.h

#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();

    QTcpServer *tcpsever;    //定义两个指针对象
    QTcpSocket *tcpsocket;
private slots:
    void on_openserver_pb_clicked();
    void new_conneciton_slot();   //server新的连接处理关联函数
    void readyRead_slot();       //socket准备读关联函数
    void on_closeserver_pb_clicked();

    void on_send_pb_clicked();

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

c.           widget.cpp

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

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    tcpsever = new QTcpServer(this);    //指针赋值
    tcpsocket = new QTcpSocket(this);

    connect(tcpsever,SIGNAL(newConnection()),this,SLOT(new_conneciton_slot()));   //新的连接函数关联
}

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

void Widget::new_conneciton_slot()    //新的连接处理函数
{
    tcpsocket=tcpsever->nextPendingConnection();
    connect(tcpsocket,SIGNAL(readyRead()),this,SLOT(readyRead_slot()));    //关联socket准备读函数
}
void Widget::readyRead_slot()        //socket准备读关联函数
{
    QString receive_buff;     //定义一个接受数组
    receive_buff=tcpsocket->readAll();    //读取所有接受的内容
    ui->receive_line->appendPlainText(receive_buff);   //在接收区显示接收到的内容
}

void Widget::on_openserver_pb_clicked() //打开服务器按钮按下处理函数
{
    tcpsever->listen(QHostAddress::Any,ui->com_number->text().toUInt());    //监听主机上的所有端口,将端口号转为无符号整型
}


void Widget::on_closeserver_pb_clicked() //关闭服务器按钮按下处理函数
{
    tcpsever->close();
}


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


4.代码

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值