QT模块学习——TCP通讯(工作过程)

QT模块学习——TCP通讯(工作过程)

工作流程

对于通讯来说,通俗点讲就是客户端先去与服务器建立通讯,也就是发出请求,而在此时一直监听着的服务器收到请求就是响应请求并同意连接,随后发送,在发送成功后readyRead()便会对应做接受处理。
QT模块学习——TCP通讯(工作过程)_第1张图片

代码

服务器

服务器需要两个套接字,监听套接字和通讯套接字

 QTcpServer *tcpsever;
    QTcpSocket *tcpsocket;

ui设计:
服务器:
QT模块学习——TCP通讯(工作过程)_第2张图片

#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
     
    ui->setupUi(this);
    tcpsever=NULL;
    tcpsocket=NULL;
    setWindowTitle("端口号为8888的服务器");
   tcpsever = new QTcpServer(this);
   tcpsever->listen(QHostAddress::Any,8888);
   connect(tcpsever,&QTcpServer::newConnection,
           [=](){
     
       tcpsocket = tcpsever->nextPendingConnection();
       //获得对方的IP和端口
       QString ip = tcpsocket->peerAddress().toString();
       qint16 port = tcpsocket->peerPort();
       QString temp = QString("[%1:%2]:成功连接").arg(ip).arg(port);
       ui->textEdit_2->setText(temp);
       connect(tcpsocket, &QTcpSocket::readyRead,
               [=](){
     
          QByteArray array=tcpsocket->readAll();
          ui->textEdit_2->append(array);
       });
   });
}


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




void Widget::on_pushButton_send_clicked()
{
     
    if(NULL==tcpsocket){
     
        return;
    }
    //获取编辑区内容
    QString str = ui->textEdit->toPlainText();
    tcpsocket->write(str.toUtf8().data());
}


void Widget::on_pushButton_2_clicked()
{
     
    tcpsocket->disconnectFromHost();//
    tcpsocket->close();
}
客户端

仅仅需要一个通讯套接字
ui界面:
QT模块学习——TCP通讯(工作过程)_第3张图片

#include "client.h"
#include "ui_client.h"
#include 
client::client(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::client)
{
     
    ui->setupUi(this);


    tcpsocket = NULL;
    tcpsocket = new QTcpSocket(this);


    connect(tcpsocket, QTcpSocket::connected,
            [=]()
    {
     
       ui->read->setText("成功与服务器建立连接");
    }
    );


    connect(tcpsocket,&QTcpSocket::readyRead,
            [=](){
     
       QByteArray array = tcpsocket->readAll();
       ui->read->setText(array);
    });
}


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


void client::on_pushButton_3_clicked()
{
     
    qint16  port = ui ->lineEdit->text().toInt();
    QString ip = ui->lineEdit_2->text();
    tcpsocket->connectToHost(QHostAddress(ip),port);//请求通讯
}
void client::on_pushButton_clicked()
{
     
    QString str = ui->write->toPlainText();
    tcpsocket->write(str.toUtf8().data());
    ui->write->clear();
}
void client::on_pushButton_2_clicked()
{
     
    tcpsocket->disconnectFromHost();
    tcpsocket->close();
}

你可能感兴趣的:(Qt,Creator模块学习,socket,网络,qt,程序人生,经验分享)