码迷,mamicode.com
首页 > 其他好文 > 详细

QT TCP客户端

时间:2020-01-10 01:25:12      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:str   sig   http   push   mamicode   xpl   button   public   void   

1、在.pro文件中加入一句

QT     += network

2、.h文件

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTcpSocket>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void readData();
    void sendData();
    void disconnecting();
    void connecting();
    void showConnect();

private:
    Ui::MainWindow *ui;
    QTcpSocket *socket;
};

#endif // MAINWINDOW_H

.cpp文件

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->pushButton_2->setEnabled(false);
    socket = new QTcpSocket;
    connect(socket,SIGNAL(readyRead()),this,SLOT(readData()));
    connect(socket,SIGNAL(connected()),this,SLOT(showConnect()));
    connect(socket,SIGNAL(disconnected()),this,SLOT(disconnecting()));
    connect(ui->pushButton,SIGNAL(clicked(bool)),this,SLOT(connecting()));
    connect(ui->pushButton_2,SIGNAL(clicked(bool)),this,SLOT(sendData()));
}

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

void MainWindow::connecting()
{
    if(ui->pushButton->text()=="连接")
    {
        QString ip = ui->lineEdit->text();
        quint16 port = ui->lineEdit_2->text().toUInt();
        socket->connectToHost(ip,port);
    }
    else
    {
        socket->close();
    }
}

void MainWindow::showConnect()
{
    ui->pushButton->setText("断开");
    ui->pushButton_2->setEnabled(true);
}

void MainWindow::readData()
{
    QByteArray data = socket->readAll();
    ui->textEdit->setText(data);
}

void MainWindow::sendData()
{
    QString str = ui->textEdit_2->toPlainText();
    socket->write(str.toStdString().c_str(),str.length());
}

void MainWindow::disconnecting()
{
    ui->pushButton->setText("连接");
    ui->pushButton_2->setEnabled(false);
}

运行结果:

技术图片

QT TCP客户端

标签:str   sig   http   push   mamicode   xpl   button   public   void   

原文地址:https://www.cnblogs.com/caozewen/p/12174008.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!