Qt套接字实现TCP通信

环境:

主机:win10

开发环境:Qt



功能:

TCP进行收发通信



界面:

Qt套接字实现TCP通信_第1张图片

源代码:

在TCPsocket.pro文件中
#-------------------------------------------------
#
# Project created by QtCreator 2018-03-21T13:40:24
#
#-------------------------------------------------
 
  
QT       += core gui
QT       += network
 
  
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
 
  
TARGET = TCPsocket
TEMPLATE = app
 
  
# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
 
  
# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0
 
  
 
  
SOURCES += main.cpp\
        mainwindow.cpp
 
  
HEADERS  += mainwindow.h
 
  
FORMS    += mainwindow.ui
 
  
在MainWindow.h文件中

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
 
  
#include 
#include 
#include 
#include 
 
  
namespace Ui {
class MainWindow;
}
 
  
class MainWindow : public QMainWindow
{
     Q_OBJECT
 
  
 public:
     explicit MainWindow(QWidget *parent = 0);
     ~MainWindow();
 
  
 private slots:
    void sendMassage();
    void readMassage();
    void displayError(QAbstractSocket::SocketError);
    void connectUpdata();
    void disconnectUpdata();
    void on_sendButton_clicked();
    void on_clearButton_clicked();
    void on_connnectButton_clicked();
    void on_disconnectButton_clicked();
 
  
 private:
    //QTcpServer *tcpServer;//不用再建立服务器类了,直接建立下面的套接字
    QTcpSocket *tcpSocket;//直接建立TCP套接字类
    QString tcpIp;//存储IP地址
    QString tcpPort;//存储端口地址
    bool flag;
 
  
    Ui::MainWindow *ui;
 
  
 };
 
  
#endif // MAINWINDOW_H
 
  

mainwindow.cpp中
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include 
 
  
MainWindow::MainWindow(QWidget *parent) :
     QMainWindow(parent),
     ui(new Ui::MainWindow)
 {
     ui->setupUi(this);
     ui->sendButton->setEnabled(false);
     ui->disconnectButton->setEnabled(false);
     ui->IPLineEdit->setText("192.168.3.4");
     ui->portLineEdit->setText("4001");
     tcpSocket = NULL;//使用前先清空
 }
 
  
 MainWindow::~MainWindow()
 {
     delete tcpSocket;
     delete ui;
 }
 
  
 void MainWindow::sendMassage(){}
 
  
 void MainWindow::readMassage()
 {
     QByteArray data=tcpSocket->readAll();
     ui->clearLineEdit->setText(QString(data));
 }
 
  
 void MainWindow::displayError(QAbstractSocket::SocketError)
 {
     QMessageBox::warning (this, tr("Warnning"), tcpSocket->errorString ());
     tcpSocket->close ();
     ui->connnectButton->setEnabled (true);
     ui->disconnectButton->setEnabled (false);
     ui->sendButton->setEnabled (false);
 }
 
  
 void MainWindow::on_sendButton_clicked()
 {
     QString sendmessage;
     sendmessage = ui->sendLineEdit->text();
    /* if(sendmessage == NULL) return;
     QByteArray block;//暂时存储我们需要发送的数据
     QDataStream out(&block,QIODevice::WriteOnly);//TCP必须和数据流一起使用
     out.setVersion(QDataStream::Qt_5_7);//设置数据流的版本(服务器和主机版本一定相同)
     out << sendmessage;
     tcpSocket->write(block);*/
     QByteArray data;
     data.append(sendmessage);
     tcpSocket->write(data);
 }
 
  
 void MainWindow::on_clearButton_clicked()
 {
     ui->clearLineEdit->clear();
 }
 
  
 void MainWindow::on_connnectButton_clicked()
 {
     flag = false;
     if(tcpSocket) delete tcpSocket;//如果有指向其他空间直接删除
     tcpSocket = new QTcpSocket(this);//申请堆空间有TCP发送和接受操作
     tcpIp = ui->IPLineEdit->text();
     tcpPort = ui->portLineEdit->text();
     if(tcpIp==NULL||tcpPort==NULL)//判断IP和PORT是否为空
     {
         QMessageBox msgBox;
         msgBox.setText("IP or PORT is Empty");
         msgBox.exec();
         return;
     }
     tcpSocket->connectToHost(tcpIp,tcpPort.toInt());//连接主机
     connect(tcpSocket,SIGNAL(error(QAbstractSocket::SocketError)),this,
             SLOT(displayError(QAbstractSocket::SocketError)));//错误连接
     connect(tcpSocket,SIGNAL(connected()),this,
             SLOT(connectUpdata()));//更新连接之后按钮的使能
     connect(tcpSocket,SIGNAL(readyRead()),this,
             SLOT(readMassage()));//读取信息的连接
     ui->connnectButton->setEnabled (false);
     ui->disconnectButton->setEnabled (true);
 
  
 }
 
  
 void MainWindow::on_disconnectButton_clicked()
 {
     tcpSocket->abort();
     delete tcpSocket;
     tcpSocket=NULL;
     disconnectUpdata();
 }
 
  
 void MainWindow::connectUpdata()
 {
     if(!flag)
     {
         QMessageBox msgBox;
         msgBox.setText("TCP connect successful");
         msgBox.exec();
         ui->connnectButton->setEnabled(false);
         ui->sendButton->setEnabled(true);
         ui->disconnectButton->setEnabled(true);
         ui->IPLineEdit->setEnabled(false);
         ui->portLineEdit->setEnabled(false);
     }
     flag=true;
 }
 
  
 void MainWindow::disconnectUpdata()
 {
     ui->connnectButton->setEnabled(true);
     ui->sendButton->setEnabled(false);
     ui->disconnectButton->setEnabled(false);
     ui->IPLineEdit->setEnabled(true);
     ui->portLineEdit->setEnabled(true);
 }
 
  

在main.cpp中
#include "mainwindow.h"
#include 
 
  
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
 
  
    return a.exec();
}


效果:

Qt套接字实现TCP通信_第2张图片

到这里,实现了TCP双向通信功能。


你可能感兴趣的:(Qt套接字实现TCP通信)