自学内容网 自学内容网

QT TCP通讯客户端与服务端

服务端

 // 自定义如下
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);

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

 客户端

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

}

 


原文地址:https://blog.csdn.net/weixin_54253218/article/details/136243184

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!