zoukankan      html  css  js  c++  java
  • qt学习(七)Sockt-TCP-UDP-BOARDCAST-MULI-CAST

    Sockt-TCP-UDP-BOARDCAST-MULI-CAST

    1.TCP

     选择要接听的网口和ip

    #ifndef CHOOSEINTERFACE_H
    #define CHOOSEINTERFACE_H
    
    #include <QDialog>
    #include <QComboBox>
    
    class ChooseInterface : public QDialog
    {
        Q_OBJECT
    public:
        explicit ChooseInterface(QWidget *parent = 0);
        QComboBox* _comboBox;
        QString _strSelect;
    signals:
    
    public slots:
    
        void slotComboBoxChange(QString);
    
    };
    
    #endif // CHOOSEINTERFACE_H
    #include "ChooseInterface.h"
    #include <QNetworkInterface>
    #include <QVBoxLayout>
    
    ChooseInterface::ChooseInterface(QWidget *parent) :
        QDialog(parent)
    {
        /* get all interface */
        QList<QHostAddress> addrList = QNetworkInterface::allAddresses();
    #if 0
        QList<QNetworkInterface> infList = QNetworkInterface::allInterfaces();
    
         QList<QNetworkAddressEntry> entryList = infList.at(0).addressEntries();
         entryList.at(0).broadcast()
    #endif
    
        _comboBox = new QComboBox;
        QVBoxLayout* lay = new QVBoxLayout(this);
        lay->addWidget(_comboBox);
    
        foreach(QHostAddress addr, addrList)
        {
            quint32 ipaddr = addr.toIPv4Address();
            if(ipaddr == 0)
                continue;
            _comboBox->addItem(QHostAddress(ipaddr).toString());
        }
    
        connect(_comboBox, SIGNAL(currentIndexChanged(QString)),
                this, SLOT(slotComboBoxChange(QString)));
    }
    
    void ChooseInterface::slotComboBoxChange(QString str)
    {
        this->_strSelect = str;
    }

    服务端

    #ifndef TCPSERVER_H
    #define TCPSERVER_H
    
    #include <QWidget>
    #include <QTcpServer>
    #include <QTcpSocket>
    #include <QTextBrowser>
    
    class TcpServer : public QWidget
    {
        Q_OBJECT
    public:
        explicit TcpServer(QWidget *parent = 0);
    
        QTcpServer* _server;
        QTcpSocket* _socket;
    
        QTextBrowser* _show;
    
    signals:
    
    public slots:
        void slotNetConnection();
        void slotReadyRead();
    
    };
    
    #endif // TCPSERVER_H
    #include "TcpServer.h"
    #include <QHBoxLayout>
    #include <QNetworkInterface>
    #include <QMessageBox>
    #include "ChooseInterface.h"
    TcpServer::TcpServer(QWidget *parent) :
        QWidget(parent)
    {
        // 创建服务器并监听
        _server = new QTcpServer;
    
        ChooseInterface dlg;
        dlg.exec();
    
        QMessageBox::information(NULL,"you select the ip:", dlg._strSelect);
    
        _server->listen(QHostAddress(dlg._strSelect), 9988);
    
        // 当有客户端来连接时,调用slotNetConnection方法
        connect(_server, SIGNAL(newConnection()),
                this, SLOT(slotNetConnection()));
    
        _show = new QTextBrowser;
        QHBoxLayout* lay = new QHBoxLayout(this);
        lay->addWidget(_show);
    }
    
    void TcpServer::slotNetConnection()
    {
        // 判断是否有未处理的连接
        while(_server->hasPendingConnections())
        {
            // 调用nextPeddingConnection去获得连接的socket
            _socket = _server->nextPendingConnection();
    
            _show->append("New connection ....");
    
            // 为新的socket提供槽函数,来接收数据
            connect(_socket, SIGNAL(readyRead()),
                    this, SLOT(slotReadyRead()));
        }
    }
    
    void TcpServer::slotReadyRead()
    {
        // 接收数据,判断是否有数据,如果有,通过readAll函数获取所有数据
        while(_socket->bytesAvailable() > 0)
        {
            _show->append("Data arrived ..... ");
            QByteArray buf = _socket->readAll();
            _show->append(buf);
        }
    }

    客户端

    #ifndef TCPCLIENT_H
    #define TCPCLIENT_H
    
    #include <QWidget>
    #include <QTcpSocket>
    #include <QLineEdit>
    
    class TcpClient : public QWidget
    {
        Q_OBJECT
    public:
        explicit TcpClient(QWidget *parent = 0);
    
        QTcpSocket* _socket;
    
        QLineEdit* _lineEdit;
    
    signals:
    
    public slots:
        void slotButtonClick();
    
    };
    
    #endif // TCPCLIENT_H
    #include "TcpClient.h"
    #include <QHBoxLayout>
    #include <QPushButton>
    TcpClient::TcpClient(QWidget *parent) :
        QWidget(parent)
    {
        _socket = new QTcpSocket(this);
        _socket->connectToHost("127.0.0.1", 9988);
    
        _lineEdit = new QLineEdit;
        QHBoxLayout* lay = new QHBoxLayout(this);
        lay->addWidget(_lineEdit);
        QPushButton* button = new QPushButton("Send");
    
        lay->addWidget(button);
        connect(button, SIGNAL(clicked()), this, SLOT(slotButtonClick()));
    
        connect(_lineEdit, SIGNAL(returnPressed()), this, SLOT(slotButtonClick()));
    }
    
    void TcpClient::slotButtonClick()
    {
        QString strText = _lineEdit->text();
        if(strText.isEmpty())
            return;
    
        _socket->write(strText.toUtf8());
        _lineEdit->clear();
    }

    主窗口

    int main(int argc, char** argv)
    {
        QApplication app(argc, argv);
    
    
      //  MyWidget w;
      //  w.show();
        TcpServer s; s.show();
        TcpClient c; c.show();
        s.setWindowTitle("server");
        c.setWindowTitle("client");
    
        return app.exec();
    }

    2.UDP

    udp1:

    #ifndef UDP1_H
    #define UDP1_H
    
    #include <QWidget>
    #include<QUdpSocket>
    class udp1 : public QWidget
    {
        Q_OBJECT
    public:
        explicit udp1(QWidget *parent = nullptr);
        QUdpSocket *_udp;
    
    signals:
    
    public slots:
        void slotReadyRead();
    };
    
    #endif // UDP1_H
    #include "udp1.h"
    #include<QTimer>
    #include<QDateTime>
    udp1::udp1(QWidget *parent) : QWidget(parent)
    {
       _udp=new QUdpSocket;
       _udp->bind(10001);
       connect(_udp,SIGNAL(readyRead()),this,SLOT(slotReadyRead()));
    
       //每隔一秒钟发送一个时间戳
       QTimer *timer=new QTimer;
       timer->setInterval(1000);
       timer->start();
       connect(timer,&QTimer::timeout,[&](){
           quint64 timestamp=QDateTime::currentMSecsSinceEpoch();
           QString str=QString::number(timestamp);
    #if 0 //普通发送
           _udp->writeDatagram(str.toUtf8(),QHostAddress("127.0.0.1"),10002);
    #else //广播和多播
    //       _udp->writeDatagram(str.toUtf8(),QHostAddress::Broadcast,10002);
           _udp->writeDatagram(str.toUtf8(),QHostAddress("224.0.0.131"),10002);
    
    #endif
       });
    }
    
    void udp1::slotReadyRead()
    {
        while(_udp->hasPendingDatagrams())
        {
            quint32 datagramSize=_udp->pendingDatagramSize();//获取数据报的大小
    
            QByteArray buf(datagramSize,0);//通过一个QByteArray申请到一块内存
            _udp->readDatagram(buf.data(),buf.size());//接收数据报文
            qDebug()<<"udp1"<<buf;
        }
    
    }

    udp2

    #ifndef UDP2_H
    #define UDP2_H
    
    #include <QWidget>
    #include<QUdpSocket>
    
    class udp2 : public QWidget
    {
        Q_OBJECT
    public:
        explicit udp2(QWidget *parent = nullptr);
        QUdpSocket *_udp;
    
    signals:
    
    public slots:
    
        void slotReadyRead();
    };
    
    #endif // UDP2_H
    #include "udp2.h"
    #include<QTimer>
    #include<QDateTime>
    udp2::udp2(QWidget *parent) : QWidget(parent)
    {
        _udp=new QUdpSocket;
        _udp->bind(QHostAddress::AnyIPv4,10002);
        connect(_udp,SIGNAL(readyRead()),this,SLOT(slotReadyRead()));
    
        _udp->joinMulticastGroup(QHostAddress("224.0.0.131"));//加入多播地址
    
    
        //每隔一秒钟发送一个时间戳
        QTimer *timer=new QTimer;
        timer->setInterval(1000);
        timer->start();
        connect(timer,&QTimer::timeout,[&](){
            quint64 timestamp=QDateTime::currentMSecsSinceEpoch();
            QString str=QString::number(timestamp);
            _udp->writeDatagram(str.toUtf8(),QHostAddress("127.0.0.1"),10001);
        });
    }
    void udp2::slotReadyRead()
    {
        while(_udp->hasPendingDatagrams())
        {
            quint32 datagramSize=_udp->pendingDatagramSize();//获取数据报的大小
    
            QByteArray buf(datagramSize,0);//通过一个QByteArray申请到一块内存
            _udp->readDatagram(buf.data(),buf.size());//接收数据报文
            qDebug()<<"udp2"<<buf;
        }
    
    }

    udp支持广播和多播。 

  • 相关阅读:
    Echarts之美国新冠疫情地图制作
    前端三件套--CSS(pink老师课程笔记)
    数据预处理与转存(Hive--Mysql)
    HDFS的命令行使用
    hdfs的写入过程和读取过程
    树(一)树的基本知识
    指针中容易混淆的概念
    顺序查找、单链表查找、折半查找
    JAVA之I/O流
    SpringBoot-自定义spring-boot-starter
  • 原文地址:https://www.cnblogs.com/rainbow1122/p/8182320.html
Copyright © 2011-2022 走看看