QT5.10控制台下利用QTcpSocket类局域网传送图片

与简单的传送一个包含字符串和int变量的结构对象不同,图片属于大文件,传送时会自动拆分为多个小包并一一传送,所以接收的时候需要多次接收并拼接。

客户端(发送):


#include <iostream>

#include <QApplication>

#include <QPixmap>/

//QT Socket
#include <QTcpSocket>
#include <QHostAddress>

#include <QBuffer>

using namespace std;

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);


    QTcpSocket socket1;

    //开始连接服务端
    socket1.connectToHost(QHostAddress("192.168.100.101"),50002);//设置连接信息,并尝试连接

    qDebug() <<"正在连接服务器,最长5秒...";
    if (socket1.waitForConnected(5000))//连接等待,如果connectToHost连接成功,则立即返回true,否则到达最延迟后返回false
    {
        qDebug() << "已连接!";
    }
    else{
        qDebug() << "连接失败!";
        socket1.close();
        return a.exec();
    }

    QPixmap Pixmap("aaa.bmp");
    QBuffer buffer;
    Pixmap.save(&buffer,"bmp");

    quint32 pix_len = (quint32)buffer.data().size();
    qDebug() << "image size:" << pix_len;

    QByteArray dataArray;
    dataArray.append(buffer.data());

    quint32 write_len = socket1.write(dataArray);
    qDebug() << "write len:" << write_len;

    if(socket1.waitForBytesWritten(10000))
    {
        qDebug() << "data发送成功!";
    }else
    {
        qDebug() << "发送超时!";
    }


    socket1.close();
    return a.exec();
}

服务端(接收):

#include <iostream>

#include <QApplication>

//QT Socket
#include <QTcpServer>
#include <QTcpSocket>
#include <QHostAddress>

#include <QPixmap>
#include <QBuffer>

using namespace std;

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);


    QTcpServer server;
    server.listen(QHostAddress::Any,50002);

    QTcpSocket * socket;

    qDebug() << "正在获取连接...最长100秒";
    if(server.waitForNewConnection(100000))
    {
        qDebug() << "连接成功!";
        socket = server.nextPendingConnection();
    }else
    {
        qDebug() << "等待连接超时!";
        server.close();
        return a.exec();
    }

    QByteArray array;
    if(socket->waitForReadyRead(100000))//等待直到有可读内容,最长100秒
    {
        while(socket->waitForReadyRead(100))
        {
            qDebug()<< "bytesAvailable";
            array.append((QByteArray)socket->readAll());//append()会拼接多个小包
        }
    }else
    {
        qDebug() << "读取等待超时!";
        server.close();
        return a.exec();
    }

    QPixmap pixmap;
    pixmap.loadFromData(array);//提取图片

    if(pixmap.save("ddd","bmp"))
        qDebug() << "保存图片成功!";

    cout << "end" << endl;
    server.close();
    return a.exec();
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
很抱歉,我不能为您提供完整的代码。但是,我可以提供一些实现的思路和关键代码,供您参考。 1. 服务器端程序 ```c++ #include <QTcpServer> #include <QTcpSocket> #include <QSerialPort> #include <QSerialPortInfo> #include <QFileInfo> #include <QDir> #include <QDataStream> #include <QDebug> class Server : public QTcpServer { Q_OBJECT public: Server(QObject *parent = nullptr) : QTcpServer(parent) { m_serialPort = new QSerialPort(this); m_serialPort->setPortName("COM1"); // 设置串口名称 m_serialPort->setBaudRate(QSerialPort::Baud115200); // 设置波特率 m_serialPort->setDataBits(QSerialPort::Data8); // 设置数据位 m_serialPort->setParity(QSerialPort::NoParity); // 设置校验位 m_serialPort->setStopBits(QSerialPort::OneStop); // 设置停止位 m_serialPort->open(QIODevice::ReadWrite); // 打开串口 connect(m_serialPort, &QSerialPort::readyRead, this, &Server::onSerialPortReadyRead); } protected: void incomingConnection(qintptr socketDescriptor) override { QTcpSocket *clientSocket = new QTcpSocket(this); clientSocket->setSocketDescriptor(socketDescriptor); connect(clientSocket, &QTcpSocket::readyRead, this, &Server::onClientReadyRead); connect(clientSocket, &QTcpSocket::disconnected, clientSocket, &QTcpSocket::deleteLater); m_clients.append(clientSocket); qDebug() << "New client connected: " << clientSocket->peerAddress().toString(); } private slots: void onClientReadyRead() { QTcpSocket *clientSocket = qobject_cast<QTcpSocket *>(sender()); if (!clientSocket) return; QByteArray data = clientSocket->readAll(); if (data.startsWith("IMAGE:")) { // 从客户端接收到图片数据 QByteArray imageData = data.mid(6); m_serialPort->write(imageData); // 发送图片数据到串口 } else { // 处理其他数据 } } void onSerialPortReadyRead() { // 从串口接收到图片数据 QByteArray imageData = m_serialPort->readAll(); QByteArray data = "IMAGE:" + imageData; // 添加标识符 broadcast(data); // 转发图片数据到所有客户端 } private: void broadcast(const QByteArray &data) { for (QTcpSocket *clientSocket : qAsConst(m_clients)) { clientSocket->write(data); } } QList<QTcpSocket *> m_clients; QSerialPort *m_serialPort; }; ``` 2. 客户端程序 ```c++ #include <QTcpSocket> #include <QSerialPort> #include <QSerialPortInfo> #include <QFileDialog> #include <QMessageBox> #include <QDataStream> #include <QDebug> class Client : public QObject { Q_OBJECT public: Client(QObject *parent = nullptr) : QObject(parent) { m_tcpSocket = new QTcpSocket(this); m_serialPort = new QSerialPort(this); m_serialPort->setPortName("COM1"); // 设置串口名称 m_serialPort->setBaudRate(QSerialPort::Baud115200); // 设置波特率 m_serialPort->setDataBits(QSerialPort::Data8); // 设置数据位 m_serialPort->setParity(QSerialPort::NoParity); // 设置校验位 m_serialPort->setStopBits(QSerialPort::OneStop); // 设置停止位 m_serialPort->open(QIODevice::ReadWrite); // 打开串口 connect(m_serialPort, &QSerialPort::readyRead, this, &Client::onSerialPortReadyRead); connect(m_tcpSocket, &QTcpSocket::readyRead, this, &Client::onTcpSocketReadyRead); connect(m_tcpSocket, &QTcpSocket::connected, this, &Client::onTcpSocketConnected); connect(m_tcpSocket, &QTcpSocket::disconnected, this, &Client::onTcpSocketDisconnected); connect(m_tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(onTcpSocketError(QAbstractSocket::SocketError))); } public slots: void connectToServer(const QString &address, quint16 port) { m_tcpSocket->connectToHost(address, port); } private slots: void onTcpSocketConnected() { qDebug() << "Connected to server: " << m_tcpSocket->peerAddress().toString(); } void onTcpSocketDisconnected() { qDebug() << "Disconnected from server"; } void onTcpSocketError(QAbstractSocket::SocketError error) { qDebug() << "Socket error: " << error; } void onTcpSocketReadyRead() { QByteArray data = m_tcpSocket->readAll(); if (data.startsWith("IMAGE:")) { // 从服务器接收到图片数据 QByteArray imageData = data.mid(6); m_serialPort->write(imageData); // 发送图片数据到串口 } else { // 处理其他数据 } } void onSerialPortReadyRead() { // 从串口接收到图片数据 QByteArray imageData = m_serialPort->readAll(); QByteArray data = "IMAGE:" + imageData; // 添加标识符 m_tcpSocket->write(data); // 发送图片数据到服务器 } private: QTcpSocket *m_tcpSocket; QSerialPort *m_serialPort; }; ``` 这里只提供了部分代码,您可以根据需求进行修改和完善。同时,由于涉及到网络和串口通信,还需要考虑一些异常情况的处理,例如网络连接断开、串口连接失败等等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值