Qt tcp通信之小demo

TCP模型

大致流程图:
在这里插入图片描述

首先使用TCP通信需要在.pro文件中加入:QT += network

一、服务端实现步骤:

  • 1、创建QTcpSever套接字对象
    m_Server = new QTcpServer();
  • 2、侦听一个端口,使得客户端可以使用这个端口来访问服务器
    m_Server->listen(QHostAddress::Any,port);
  • 3、当服务器被客户端访问时,会发出newConnection()信号,并用一个QTcpSocket对象接受客户端访问,然后关联客户端收发消息
    connect(m_Server,SIGNAL(newConnection()),this,SLOT(dealnewConnection()));
    void Widget::dealnewConnection()
    {
    //与客户端通信的套接字
    m_Socket = m_Server->nextPendingConnection();
    }
  • 4、当socket接收缓冲区有新数据到来时,readRead()信号以读取数据
    //可以实现同时读取多个客户端发送过来的消息
    QTcpSocket obj = (QTcpSocket)sender();
    QString msg = obj->readAll();//读取消息
  • 5、可使用socket的write函数向客户端发送数据
    m_Socket->write(data);
  • 6、取消侦听
    server->close();

二、客户端实现步骤:

  • 1、创建QTcpSocket套接字对象
    m_Socket = new QTcpSocket();
    //关联数据信号
    connect(m_Socket,SIGNAL(connected()),this,SLOT(dealconnected()));
  • 2、使用这个对象连接服务器
    m_Socket->connectToHost(IP, port);
  • 3、使用write函数向服务器发信息
    m_Socket->write(data);
  • 4、当m_Socket接收缓冲区有新数据到来时,会发出readRead()信号
    connect(m_Socket,SIGNAL(readyRead()),this,SLOT(dealreadyRead()));
    void client::dealreadyRead()
    {
    QString msg = m_Socket->readAll();
    }

三、实现代码

服务器.h文件

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

#include <QTcpServer>
#include <QTcpSocket>

#include <QModelIndex>
#include <QList>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = NULL);
    ~Widget();
    void updateList();
private slots:
    void on_pushButton_send_2_clicked();

    void on_pushButton_set_clicked();

    void dealnewConnection();
    void dealreadyRead();
    void dealdisconnected();

    void dealclicked(QModelIndex);


    void on_pushButton_clicked();

private:
    Ui::Widget *ui;
    QTcpServer *m_Server;
    QTcpSocket *m_Socket;

    QList<QTcpSocket*> m_list;
    QTcpSocket *m_SocketNow = NULL;
    QStringList m_listStr;
    int  m_cnt;

};
#endif // WIDGET_H

服务器.cpp文件

#include "widget.h"
#include "ui_widget.h"
#include <QHostInfo>
#include <QNetworkInterface>
#include <QDateTime>
#include <QStandardItemModel>
#include <QStringListModel>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    /*设置不可编辑*/
    ui->listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    /*获取本机ip*/
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
    /*use the first non-localhost IPv4 address*/
    QString ipAddress;
    for (int i = 0; i < ipAddressesList.size(); ++i) {
        qDebug()<<ipAddressesList.at(i);
        if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
            ipAddressesList.at(i).toIPv4Address()) {
            ipAddress = ipAddressesList.at(i).toString();
            break;
        }
    }
    ui->label_seriviceIp->setText("本级ip:"+ipAddress);
}

void Widget::on_pushButton_set_clicked()
{
    /*初始化服务器server对象*/
    m_Server = new QTcpServer();
    /*启动服务器监听*/
    m_Server->listen(QHostAddress::Any,ui->lineEdit_Setport->text().toInt());
    /*关联客户端连接信号newConnection*/
    connect(m_Server,SIGNAL(newConnection()),this,SLOT(dealnewConnection()));
    ui->pushButton_set->setEnabled(false);
}

void Widget::dealnewConnection()
{
    /*与客户端通信的套接字*/
    m_Socket = m_Server->nextPendingConnection();
    /*获取客户端ip*/
    QString ip = m_Socket->peerAddress().toString();
    /*关联接收客户端数据信号readyRead信号(客户端有数据就会发readyRead信号)*/
    connect(m_Socket,SIGNAL(readyRead()),this,SLOT(dealreadyRead()));
    /*检测掉线信号*/
    connect(m_Socket,SIGNAL(disconnected()),this,SLOT(dealdisconnected()));
    /*同一ip打开了两次,以区分*/
    m_listStr.append(QString("%1").arg(m_cnt) + "#" + ip );
    m_cnt ++;
    m_list.append(m_Socket);
    updateList();

    ui->textBrowser->append("客户端" + ip + "连接!" );
}


void Widget::dealreadyRead()
{
    /*可以实现同时读取多个客户端发送过来的消息*/
    QTcpSocket *obj = (QTcpSocket*)sender();
    /*获取ip*/
    QString ip = obj->peerAddress().toString();
    /*读取消息*/
    QString msg = obj->readAll();
    /*获取当前时间*/
    QDateTime current_date_time =QDateTime::currentDateTime();
    QString current_date =current_date_time.toString("hh:mm:ss");
    ui->textBrowser->append(QString("客户端%1\t %2").arg(ip).arg(current_date));
    ui->textBrowser->append(QString("%1").arg(msg));
}

void Widget::on_pushButton_send_2_clicked()
{
    if(!m_SocketNow)
    {
        ui->label->setText("没有选择客户端!");
        return;
    }
    else if(ui->lineEdit_information_2->text() == "")
    {
        ui->label->setText("发送内容为空!");
        return;
    }
    /*取发送信息编辑框内容*/
    QString msg = ui->lineEdit_information_2->text();
    /*转编码*/
    m_SocketNow->write(msg.toUtf8());
    QString ip = m_SocketNow->peerAddress().toString();
    QDateTime current_date_time =QDateTime::currentDateTime();
    QString current_date =current_date_time.toString("hh:mm:ss");
    ui->textBrowser->append(QString("发送消息到%1\t %2").arg(ip).arg(current_date));
    ui->textBrowser->append(msg);
}

void Widget::dealdisconnected()
{
    QTcpSocket *obj = (QTcpSocket*)sender();//掉线对象
    QString ip = obj->peerAddress().toString();//打印出掉线对象的ip
    ui->textBrowser->append("客户端" + ip + "断开连接!" );
    for(int i=0; i<m_list.length(); i++)
    {
        if(obj == m_list.at(i))
        {
            m_listStr.removeAt(i);
            m_list.removeAt(i);
        }
    }
    updateList();
}

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

void Widget::updateList()
{
    ui->label_status_3->setText(QString("当前连接数:%1").arg(m_listStr.length()));
    if(m_listStr.length() == 0)
    {
        m_SocketNow = NULL;
        ui->label->clear();
    }
    QStringListModel *Model = new QStringListModel(m_listStr);
    ui->listView->setModel(Model);
    ui->listView->setModel(Model);
    connect(ui->listView,SIGNAL(clicked(QModelIndex)),this,SLOT(dealclicked(QModelIndex)));
}

void Widget::dealclicked(QModelIndex index)
{
    QString str = index.data().toString();
    ui->label->setText("接收客户端ip:" + str);
    for( int i=0; i<m_listStr.length(); i++)
    {
        if(m_listStr.at(i) == str)
            m_SocketNow = m_list.at(i);
    }
}

void Widget::on_pushButton_clicked()
{
    if(!m_SocketNow)
        return;
    m_SocketNow->disconnectFromHost();
    for(int i=0; i<m_list.length(); i++)
    {
        if(m_SocketNow == m_list.at(i))
        {
            m_listStr.removeAt(i);
            m_list.removeAt(i);
        }
    }
    updateList();
}

客户端.h文件

#ifndef CLIENT_H
#define CLIENT_H

#include <QWidget>

#include <QTcpServer>
#include <QTcpSocket>
namespace Ui {
class client;
}

class client : public QWidget
{
    Q_OBJECT

public:
    explicit client(QWidget *parent = NULL);
    ~client();

private slots:
    void on_pushButton_connect_clicked();

    void on_pushButton_disconnect_clicked();

    void on_pushButton_send_clicked();

    void dealreadyRead();
    void dealconnected();
    void dealdisconnected();
private:
    Ui::client *ui;

    QTcpServer *m_Server;
    QTcpSocket *m_Socket = NULL;
};

#endif // CLIENT_H

客户端.cpp文件

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

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

void client::on_pushButton_connect_clicked()
{
    /*初始化套接字对象*/
    m_Socket = new QTcpSocket(this);
    /*检测链接成功信号关联槽函数*/
    connect(m_Socket,SIGNAL(connected()),this,SLOT(dealconnected()));
    /*连接服务器,设置ip和端口号*/
    m_Socket->connectToHost(ui->lineEdit_ip->text(),ui->lineEdit_port->text().toInt());
}

void client::on_pushButton_disconnect_clicked()
{
    if(m_Socket == NULL)
        return;
    m_Socket->disconnectFromHost();
    m_Socket = NULL;
    ui->pushButton_connect->setEnabled(true);
    ui->pushButton_disconnect->setEnabled(false);
}

void client::on_pushButton_send_clicked()
{
    if(!m_Socket)
    {
        ui->lineEdit_information->clear();
        ui->lineEdit_information->setPlaceholderText("没有连接服务器!");
        return;
    }else if(ui->lineEdit_information->text() == "")
    {
        ui->lineEdit_information->clear();
        ui->lineEdit_information->setPlaceholderText("发送内容为空!");
        return;
    }
    /*取发送信息编辑框内容*/
    QString msg = ui->lineEdit_information->text();
    /*转编码*/
    m_Socket->write(msg.toUtf8());
    QDateTime current_date_time =QDateTime::currentDateTime();
    QString current_date =current_date_time.toString("hh:mm:ss");
    ui->textBrowser->append("发送消息:\t"+current_date);
    ui->textBrowser->append(msg);
}

void client::dealreadyRead()
{
    QString msg = m_Socket->readAll();
    /*获取当前时间*/
    QDateTime current_date_time =QDateTime::currentDateTime();
    QString current_date =current_date_time.toString("hh:mm:ss");
    ui->textBrowser->append("接收消息:\t"+current_date);
    ui->textBrowser->append(msg);

}

void client::dealconnected()
{
    /*关联数据信号*/
    connect(m_Socket,SIGNAL(readyRead()),this,SLOT(dealreadyRead()));
    /*检测掉线信号*/
    connect(m_Socket,SIGNAL(disconnected()),this,SLOT(dealdisconnected()));
    ui->pushButton_connect->setEnabled(false);
    ui->pushButton_disconnect->setEnabled(true);
    ui->label_status->setText("服务器连接成功!");
}

void client::dealdisconnected()
{
    m_Socket = NULL;
    ui->label_status->setText("服务器连接断开!");
    ui->pushButton_connect->setEnabled(true);
    ui->pushButton_disconnect->setEnabled(false);
}

四、实现图

在这里插入图片描述

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值