13.IO

#ifndef MYWIDGET_H
#define MYWIDGET_H

#include <QWidget>

class MyWidget : public QWidget
{
    Q_OBJECT
public:
    explicit MyWidget(QWidget *parent = 0);

signals:

public slots:

};

#endif // MYWIDGET_H
#include "MyWidget.h"
#include <QFile>
#include <QApplication>
#include <QDebug>
#include <QBuffer>
#include <QLabel>
#include <QTextStream>
#include <QDataStream>
#include "TcpServer.h"
#include "TcpClient.h"
#include "udp1.h"
#include "udp2.h"
/*
    QFile
    QBuffer // memory file
    QTcpSocket
    QUdpSocket

    QDataStream  // io method
    QTextStream
*/

MyWidget::MyWidget(QWidget *parent) :
    QWidget(parent)
{
#if 0
    QFile file("../MyTest.txt");
    file.open(QIODevice::ReadWrite);

    file.write(QByteArray("abc"));
    // file.seek
   // file.write()

    file.close();
#endif

#if 0
    QBuffer buffer;
    buffer.open(QIODevice::ReadWrite);

    buffer.write("abc");
    buffer.write("aabbcc");

    buffer.close();

    qDebug() << buffer.buffer();
#endif

#if 0
    // send side
    QBuffer buffer;
    buffer.open(QIODevice::ReadWrite);
    QPixmap pixmap("../aaa.png");
    pixmap.save(&buffer, "PNG");
    buffer.close();

    qDebug() << buffer.buffer().size();

    // recv side
    QPixmap pixmap2;
    pixmap2.loadFromData(buffer.buffer(), "PNG");

    QLabel* label = new QLabel(this);
    label->setPixmap(pixmap2);
#endif


#if 0
    QByteArray ba("薛国良");
    QString str("薛国良");

    qDebug() << ba.size() << str.size();
#endif

#if 0
    QFile file("../teststream.txt");
    file.open(QIODevice::ReadWrite);

    QTextStream textStream(&file);

    textStream << 1 << "abc" << 1.2 << QString("abc");

    file.close();
#endif
#if 0
    QFile file("../datastream.txt");
    file.open(QIODevice::ReadWrite);

    QDataStream dataStream(&file);

    dataStream << 1 << "abc" << 1.2 << QString("abc") << QPoint(1, 1);

    file.close();
#endif

#if 0
    QFile file("../datastream.txt");
    file.open(QIODevice::ReadWrite);

    QDataStream dataStream(&file);

    int i;
    char* buf;
    double d;
    QString str;
    QPoint pt;

    dataStream >> i >> buf >> d >> str >> pt;

    delete[] buf;

    qDebug() << i << buf << d << str << pt;
    file.close();

#endif

#if 0
    // virtual memory
    QFile file("../map.txt");

    file.open(QIODevice::ReadWrite);
    file.seek(65535);
    file.write("1");
    file.close();
    file.open(QIODevice::ReadWrite);

    uchar* ptr = file.map(0, 64*1024);

    // write file
    *ptr = 'a';
    ptr[1] = 'b';

    // read file
    uchar ch = *ptr;

    file.unmap(ptr);
    file.close();
#endif
}

int main(int argc, char** argv)
{
    QApplication app(argc, argv);

#if 0
  //  MyWidget w;
  //  w.show();
    TcpServer s; s.show();
    TcpClient c; c.show();
    s.setWindowTitle("server");
    c.setWindowTitle("client");
#endif
    Udp1 udp1; udp1.show();
    Udp2 udp2; udp2.show();
    udp1.setWindowTitle("udp1");
    udp2.setWindowTitle("udp2");

    return app.exec();
}


#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 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 "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 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
#ifndef UDP1_H
#define UDP1_H

#include <QWidget>
#include <QUdpSocket>

class Udp1 : public QWidget
{
    Q_OBJECT
public:
    explicit Udp1(QWidget *parent = 0);
    QUdpSocket* _udp;

signals:

public slots:
    void slotReadyRead();
};

#endif // UDP1_H
#include "udp1.h"
#include <QTimer>
#include <QDateTime>
Udp1::Udp1(QWidget *parent) :
    QWidget(parent)
{
    // 创建udpsocket,并连接槽函数,用来接收数据
    _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
        // 普通UDPsocket发送
        _udp->writeDatagram(str.toUtf8(), QHostAddress("127.0.0.1"), 10002);
#else
        // 广播发送,注意:QHostAddress::Broadcast是255.255.255.255, 192.168.6.255
     //   _udp->writeDatagram(str.toUtf8(), QHostAddress::Broadcast, 10002);

        // multicast, 224.0.0.1~224.0.0.255 is multicast address of LAN
        _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);
        _udp->readDatagram(buf.data(), buf.size());
        qDebug() <<"Udp1"<< buf;
    }
}
#ifndef UDP2_H
#define UDP2_H

#include <QWidget>
#include <QUdpSocket>
class Udp2 : public QWidget
{
    Q_OBJECT
public:
    explicit Udp2(QWidget *parent = 0);
    QUdpSocket* _udp;

signals:

public slots:
    void slotReadyRead();

};

#endif // UDP2_H
#include "udp2.h"
#include <QTimer>
#include <QDateTime>

#include <QLineEdit>

Udp2::Udp2(QWidget *parent) :
    QWidget(parent)
{
    _udp = new QUdpSocket;

    // the address of bind and multicast must be same tpye(IPV4 or IPV6)
    _udp->bind(QHostAddress::AnyIPv4, 10002);

    // join the multicast address (224.0.0.131) for recv mulicast package
    _udp->joinMulticastGroup(QHostAddress("224.0.0.131"));

    connect(_udp, SIGNAL(readyRead()),
            this, SLOT(slotReadyRead()));

    QTimer* timer = new QTimer(this);
    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);
        _udp->readDatagram(buf.data(), buf.size());
        qDebug() << "Udp2" <<buf;
    }
}

猜你喜欢

转载自blog.csdn.net/sunxiaopengsun/article/details/82931449