QT TCP通讯客户端与服务端

服务端

cpp 复制代码
 // 自定义如下
private:
    QTcpServer *tcpserver; //TCP服务器
    QTcpSocket *tcpsocket;// TCP通讯socket
    QString GetLocalIpAddress(); // 获取本机的IP地址

private slots:
    void clientconnect();
    void clientdisconnect();
    void socketreaddata();
    void newconnection();



    void on_pushButton_Start_clicked();
    void on_pushButton_Stop_clicked();
    void on_pushButton_Send_clicked();

protected:
    void closeEvent(QCloseEvent *event);
cpp 复制代码
#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QMessageBox>
#pragma execution_character_set("utf-8")
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QString strip=GetLocalIpAddress();
    // QMessageBox::information(this,"数据",strip,QMessageBox::Yes);

    ui->comboBoxIp->addItem(strip);


    tcpserver=new QTcpServer(this);

    connect(tcpserver,SIGNAL(newConnection()),this,SLOT(newconnection()));




}

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


void MainWindow::on_pushButton_Start_clicked()
{
    QString ip=ui->comboBoxIp->currentText();
    quint16 port=ui->spinBoxPort->value();

    QHostAddress address(ip);
    tcpserver->listen(address,port);

    ui->plainTextEdit_DispMsg->appendPlainText("$$$$$$$$$$开始监听$$$$$$$$$$");
    ui->plainTextEdit_DispMsg->appendPlainText("$$$$$$$$$$服务器地址$$$$$$$$$$:"+
                                               tcpserver->serverAddress().toString());
    ui->plainTextEdit_DispMsg->appendPlainText("$$$$$$$$$$服务器端口$$$$$$$$$$:"+
                                               QString::number(tcpserver->serverPort()));
    ui->pushButton_Start->setEnabled(false);
    ui->pushButton_Stop->setEnabled(true);

}

void MainWindow::on_pushButton_Stop_clicked()
{
    if(tcpserver->isListening())
    {
        tcpserver->close();
        ui->pushButton_Start->setEnabled(true);
        ui->pushButton_Stop->setEnabled(false);
    }

}

void MainWindow::on_pushButton_Send_clicked()
{
    QString strmsg=ui->lineEdit_InputMsg->text();
    ui->plainTextEdit_DispMsg->appendPlainText("[out]:"+strmsg);

    ui->lineEdit_InputMsg->clear();

    QByteArray str=strmsg.toUtf8();
    str.append("\n");
    tcpsocket->write(str);
}


QString MainWindow::GetLocalIpAddress() // 获取本机的IP地址
{
    QString hostname=QHostInfo::localHostName();
    QHostInfo hostinfo=QHostInfo::fromName(hostname);

    QString localip="";

    QList<QHostAddress> addresslist=hostinfo.addresses();

    if(!addresslist.isEmpty())
    {
        for (int i=0;i<addresslist.count();i++)
        {
            QHostAddress addrhost=addresslist.at(i);
            if(QAbstractSocket::IPv4Protocol==addrhost.protocol())
            {
                localip=addrhost.toString();
                break;
            }

        }
    }

    return localip;
}

void MainWindow::clientconnect()
{
    // 客户端连接
    ui->plainTextEdit_DispMsg->appendPlainText("**********客户端socket连接**********");
    ui->plainTextEdit_DispMsg->appendPlainText("**********peer address:"+
                                               tcpsocket->peerAddress().toString());
    ui->plainTextEdit_DispMsg->appendPlainText("**********peer port:"+
                                               QString::number(tcpsocket->peerPort()));

}

void MainWindow::clientdisconnect()
{
    // 客户端断开连接
    ui->plainTextEdit_DispMsg->appendPlainText("**********客户端socket断开连接**********");
    tcpsocket->deleteLater();

}

void MainWindow::socketreaddata()
{
    // 读取数据
    while(tcpsocket->canReadLine())
        ui->plainTextEdit_DispMsg->appendPlainText("[in]"+tcpsocket->readLine());

}

void MainWindow::newconnection()
{
    tcpsocket=tcpserver->nextPendingConnection();

    connect(tcpsocket,SIGNAL(connected()),this,SLOT(clientconnect()));
    clientconnect();

    connect(tcpsocket,SIGNAL(disconnected()),this,SLOT(clientdisconnect()));

    connect(tcpsocket,SIGNAL(readyRead()),this,SLOT(socketreaddata()));

    connect(tcpsocket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),
            this,SLOT(OnSocketStateChanged(QAbstractSocket::SocketState)));


}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if(tcpserver->isListening())
        tcpserver->close();

    event->accept();
}

客户端

cpp 复制代码
private:
    QTcpSocket *tcpclient;//客户端tcpclient
    QString getLocalIp();//获取本机IP地址

protected:
    void closeEvent(QCloseEvent *event);

private slots:
    void connectFunc();
    void disConnectFunc();
    void socketReadData();


    void on_pushButton_Connect_clicked();
    void on_pushButton_DisConnect_clicked();
    void on_pushButton_Send_clicked();
cpp 复制代码
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QDebug>
#pragma execution_character_set("utf-8")
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    tcpclient=new QTcpSocket(this);
    QString strip=getLocalIp();
    ui->comboBoxIp->addItem(strip);

    connect(tcpclient,SIGNAL(connected()),this,SLOT(connectFunc()));
    connect(tcpclient,SIGNAL(disconnected()),this,SLOT(disConnectFunc()));
    connect(tcpclient,SIGNAL(readyRead()),this,SLOT(socketReadData()));


}

MainWindow::~MainWindow()
{
    delete ui;
}
//获取本机IP
QString MainWindow::getLocalIp()
{
    QString hostname=QHostInfo::localHostName();
    QHostInfo hostinfo=QHostInfo::fromName(hostname);

    QString localip="";

    QList<QHostAddress> addlist=hostinfo.addresses();
    if(!addlist.isEmpty())
    {
        for(int i=0;i<addlist.count();i++)
        {
            QHostAddress ahost=addlist.at(i);
            if(QAbstractSocket::IPv4Protocol==ahost.protocol())
            {
                localip=ahost.toString();
                break;
            }
        }
    }
    return localip;
}

void MainWindow::closeEvent(QCloseEvent *event)
{

    if(tcpclient->state()==QAbstractSocket::ConnectedState)
    {
        tcpclient->disconnectFromHost();

    }
    event->accept();
}

void MainWindow::connectFunc()
{

    ui->plainTextEdit_DispMsg->appendPlainText("*********已连接到服务器*********");
    ui->plainTextEdit_DispMsg->appendPlainText("*********peer address:"+
                                               tcpclient->peerAddress().toString());
    ui->plainTextEdit_DispMsg->appendPlainText("*********peer port:"+
                                               QString::number(tcpclient->peerPort()));

    ui->pushButton_Connect->setEnabled(false);
    ui->pushButton_DisConnect->setEnabled(true);
}

void MainWindow::disConnectFunc()
{

    ui->plainTextEdit_DispMsg->appendPlainText("*********已断开与服务器的连接*********");

    ui->pushButton_Connect->setEnabled(true);
    ui->pushButton_DisConnect->setEnabled(false);
}

void MainWindow::socketReadData()
{

    while(tcpclient->canReadLine())
    {
        qDebug()<<123;
        ui->plainTextEdit_DispMsg->appendPlainText("[in]:"+tcpclient->readLine());

    }
}

void MainWindow::on_pushButton_Connect_clicked()
{

    QString addr=ui->comboBoxIp->currentText();
    quint16 port=ui->spinBoxPort->value();
    tcpclient->connectToHost(addr,port);
}


void MainWindow::on_pushButton_DisConnect_clicked()
{

    if(tcpclient->state()==QAbstractSocket::ConnectedState)
    {
        tcpclient->disconnectFromHost();

    }
}


void MainWindow::on_pushButton_Send_clicked()
{

    QString strmsg=ui->lineEdit_InputMsg->text();
    ui->plainTextEdit_DispMsg->appendPlainText("[out]:"+strmsg);
    ui->lineEdit_InputMsg->clear();

    QByteArray str=strmsg.toUtf8();
    str.append('\n');
    tcpclient->write(str);
    qDebug()<<str;

}
相关推荐
StringerChen28 分钟前
Qt ui提升窗口的头文件找不到
开发语言·qt
xserver22 小时前
ensp 基于EASY IP的公司出口链路配置
网络·tcp/ip·智能路由器
沐泽Mu2 小时前
嵌入式学习-QT-Day07
c++·qt·学习·命令模式
沐泽Mu3 小时前
嵌入式学习-QT-Day09
开发语言·qt·学习
手心里的白日梦3 小时前
UDP传输层通信协议详解
网络·网络协议·udp
红米饭配南瓜汤3 小时前
WebRTC服务质量(11)- Pacer机制(03) IntervalBudget
网络·网络协议·音视频·webrtc·媒体
萧瑟其中~6 小时前
计算机网络:TCP/IP网络协议
网络协议·tcp/ip·计算机网络
IT 古月方源6 小时前
ensp 关于ARRP 的讲解 配置
运维·开发语言·网络·tcp/ip·智能路由器
林枫依依6 小时前
如何让Tplink路由器自身的IP网段 与交换机和电脑的IP网段 保持一致?
网络·tcp/ip·智能路由器
极客小张7 小时前
基于STM32的智慧农业控制系统设计:python可视化、UART、I2C、TCP/HTTP技术
python·stm32·单片机·物联网·tcp/ip·毕业设计·课程设计