Qt TCP服务端、客户端;QTcpSocket

服务端:

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QTcpServer>
#include <QTcpSocket>
#include <QAbstractSocket>
#include <QString>
#include <QDebug>

QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();

private:
    Ui::Widget *ui;
    QTcpServer *tcpServer;

    //槽函数来接收客户端的连接请求;
private slots:
    void mNewConnection();
    void receiveMessage();
    void mStateChanged(QAbstractSocket::SocketState);
    void on_pushButton_3_clicked();
    void on_pushButton_clicked();
    void on_pushButton_2_clicked();
};
#endif // WIDGET_H

widget.cpp 

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("服务端");
    //设置初始不可用
    ui->pushButton_2->setEnabled(false);
    tcpServer = new QTcpServer(this);
    connect(tcpServer,SIGNAL(newConnection()),this,SLOT(mNewConnection()));
}

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

void Widget::mNewConnection()
{
    //与客户端连接;
    QTcpSocket *temTcpSocket = tcpServer->nextPendingConnection();

    //打印ip地址;
    QString ipAddr = temTcpSocket->peerAddress().toString();
    ui->textBrowser->append("客户端IP地址:"+ipAddr);
    //打印port地址;
    quint16 port = temTcpSocket->peerPort();
    ui->textBrowser->append("客户端port地址:"+QString::number(port));

    connect(temTcpSocket,SIGNAL(readyRead()),this,SLOT(receiveMessage()));
    //
    connect(temTcpSocket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),
            this,SLOT(mStateChanged(QAbstractSocket::SocketState)));
}

//接收消息
void Widget::receiveMessage()
{
    //接收消息并打印;
    QTcpSocket *temTcpSocket = (QTcpSocket*)sender();
    ui->textBrowser->append("客户端:"+temTcpSocket->readAll());
}

void Widget::mStateChanged(QAbstractSocket::SocketState state)
{
    QTcpSocket *temTcpSocket = (QTcpSocket *)sender();
    switch (state) {
    case QAbstractSocket:: UnconnectedState:
        ui->textBrowser->append("客户端断开");
        //断开释放内存;
       temTcpSocket->deleteLater();
        break;
       //经调试,这句话不会打印;
    case QAbstractSocket:: ConnectedState:
         ui->textBrowser->append("客户端已连接");
        break;
    default:
        break;
    }
}

//发送信息;
void Widget::on_pushButton_3_clicked()
{
    //通过容器向所有的客户端发送信息;
    QList <QTcpSocket*> socketList = tcpServer->findChildren<QTcpSocket*>();
    qDebug()<<"客户端的数量:"<<socketList.count()<<endl;
    if(socketList.count() == 0)
    {
        ui->textBrowser->append("没有客户端连接!");
        return;
    }

    foreach(QTcpSocket *temSocket,socketList)
    {
        temSocket->write(ui->lineEdit->text().toUtf8());
    }
    ui->textBrowser->append("服务端:"+ui->lineEdit->text().toUtf8());
}
//连接客户端;
void Widget::on_pushButton_clicked()
{
    tcpServer->listen(QHostAddress("192.168.128.22"),9999);
    ui->textBrowser->append("开始监听...");
    ui->pushButton_2->setEnabled(true);
    ui->pushButton->setEnabled(false);
}
//停止监听
void Widget::on_pushButton_2_clicked()
{
    tcpServer->close();
    ui->pushButton_2->setEnabled(false);
    ui->pushButton->setEnabled(true);
}

客户端:

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QTcpSocket>
#include <QAbstractSocket>
#include <QHostAddress>

QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();

private:
    Ui::Widget *ui;
    QTcpSocket *tcpSocket;

private slots:
    void receiveMessage();
    void mStateChange(QAbstractSocket::SocketState state);
    void on_pushButton_3_clicked();
    void on_pushButton_clicked();
    void on_pushButton_2_clicked();
};
#endif // WIDGET_H

widget.cpp

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("客户端");
    ui->pushButton_2->setEnabled(false);
    tcpSocket = new QTcpSocket(this);
    connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(receiveMessage()));
    connect(tcpSocket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),
            this,SLOT(mStateChange(QAbstractSocket::SocketState)));
}

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

//客户端收到消息后,会触发槽函数,接收信息并打印出来;
void Widget::receiveMessage()
{
    ui->textBrowser->append("服务端:"+tcpSocket->readAll());
}

void Widget::mStateChange(QAbstractSocket::SocketState state)
{
    switch (state)
    {
    case QAbstractSocket::UnconnectedState:
        ui->textBrowser->append("已断开");
        ui->pushButton_2->setEnabled(false);
        ui->pushButton->setEnabled(true);
        break;
    case QAbstractSocket::ConnectedState:
        ui->textBrowser->append("已连接");
        ui->pushButton_2->setEnabled(true);
        ui->pushButton->setEnabled(false);
        break;
    default:
        break;
    }
}

//发送消息;
void Widget::on_pushButton_3_clicked()
{
    if(tcpSocket->state() == QAbstractSocket::ConnectedState)
    {
        tcpSocket->write(ui->lineEdit->text().toUtf8());
        ui->textBrowser->append("客户端:"+ui->lineEdit->text().toUtf8());
    }
    else {
        ui->textBrowser->append("未连接,请先连接服务器!");
    }
}
//连接服务器
void Widget::on_pushButton_clicked()
{
    tcpSocket->connectToHost(QHostAddress("192.168.128.22"),9999);

}
//断开服务器
void Widget::on_pushButton_2_clicked()
{
    tcpSocket->disconnectFromHost();
}

最终效果:

  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值