Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. Mobile and Embedded
  4. Error TCP and UDP
Forum Updated to NodeBB v4.3 + New Features

Error TCP and UDP

Scheduled Pinned Locked Moved Unsolved Mobile and Embedded
8 Posts 3 Posters 572 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • P Offline
    P Offline
    Patar
    wrote on 4 Jun 2024, 08:09 last edited by Patar 6 Apr 2024, 08:12
    #1

    i make a TCP and UDP Program. when UDP for messaging, than TCP for file transfer. when i run it in deskop its perfectly fine, but when i deploy there is an error like
    UDP cant connected
    TCP connected but cant receive file (always in 99% never 100%)
    heres coding for UDP and TCP connection for my server

    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow),
        localFile(nullptr)
    {
        ui->setupUi(this);
        initTcpServer();
        initUdpServer();
    }
    
    void MainWindow::initTcpServer()
    {
        tcpServer = new QTcpServer(this);
        connect(tcpServer, &QTcpServer::newConnection, this, &MainWindow::acceptTcpConnection);
        if (!tcpServer->listen(QHostAddress::Any, 8081)) {
            QMessageBox::critical(this, "QTCP Server", "Unable to start the server.");
        }
    }
    
    void MainWindow::acceptTcpConnection()
    {
        tcpSocket = tcpServer->nextPendingConnection();
        connect(tcpSocket, &QTcpSocket::readyRead, this, &MainWindow::readTcpData);
        connect(tcpSocket, &QTcpSocket::disconnected, this, [this]()
        {
            ui->statusCurrent->setText("Disconnected");
        });
    
        ui->statusCurrent->setText("Connected");
    }
    
    void MainWindow::initUdpServer()
    {
        udpSocket = new QUdpSocket(this);
        udpSocket->bind(QHostAddress::Any, 8181);
        connect(udpSocket, &QUdpSocket::readyRead, this, &MainWindow::readUdpData);
    }
    
    void MainWindow::readUdpData()
    {
        while (udpSocket->hasPendingDatagrams()) {
            QByteArray datagram;
            datagram.resize(int(udpSocket->pendingDatagramSize()));
            udpSocket->readDatagram(datagram.data(), datagram.size());
            // Here, add your logic to handle received datagram
    
        }
    }
    
    void MainWindow::startTransferFile()
    {
        if (!localFile) {
            localFile = new QFile(fileName);
            if (!localFile->open(QFile::ReadOnly)) {
                QMessageBox::critical(this, "QTCP Server", "Unable to open the file.");
                return;
            }
            totalBytes = localFile->size();
        }
    
        QByteArray buffer;
        QDataStream out(&buffer, QIODevice::WriteOnly);
        out.setVersion(QDataStream::Qt_5_15);
    
        QString currentFileName = fileName.section('/', -1);
        out << qint64(0) << qint64(0) << currentFileName;
    
        totalBytes += buffer.size();
        out.device()->seek(0);
        out << totalBytes << qint64((buffer.size() - sizeof(qint64) * 2));
        bytesToWrite = totalBytes - tcpSocket->write(buffer);
    
        while (!localFile->atEnd()) {
            buffer = localFile->read(qMin(bytesToWrite, qint64(4 * 1024)));
            bytesToWrite -= tcpSocket->write(buffer);
        }
    
        localFile->close();
        delete localFile;
        localFile = nullptr;
    }
    

    and here is my code for client

    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow),
        tcpClient(new QTcpSocket(this)),
        udpReader(new QUdpSocket(this)),
        totalBytes(0),
        bytesReceived(0),
        fileTransferInProgress(false),
        localFile(nullptr)
    {
        ui->setupUi(this);
        udpReader->bind(QHostAddress::Any, 8080, QUdpSocket::ShareAddress);
        connect(udpReader, &QUdpSocket::readyRead, this, &MainWindow::readUDPMessage);
    
        connect(tcpClient, &QTcpSocket::readyRead, this, &MainWindow::readTCPData);
        connect(tcpClient, &QTcpSocket::errorOccurred, this, &MainWindow::displayError);
    
        connectToServer();
    }
    
    void MainWindow::connectToServer()
    {
        //tcpClient->connectToHost("10.147.17.205", 8081);
        tcpClient->connectToHost("192.168.11.104", 8081);
    }
    
    void MainWindow::readUDPMessage()
    {
        while (udpReader->hasPendingDatagrams()) {
            QByteArray datagram;
            datagram.resize(int(udpReader->pendingDatagramSize()));
            udpReader->readDatagram(datagram.data(), datagram.size());
            ui->textBrowser->append(tr("Received UDP message: %1").arg(QString::fromUtf8(datagram)));
    
            //QPixmap pic("C:/Fadli/Kuliah/Semester 6/Reka/4.QT/coba/" + QString::fromUtf8(datagram) + ".png");
            //QPixmap pic("file:///storage/emulated/0/DCIM/Camera/IMG" + QString::fromUtf8(datagram));// HP
            QPixmap pic("storage/emulated/0/Download/" + QString::fromUtf8(datagram));// AVD
    
            // Menyesuaikan skala gambar
            QPixmap scaledPic = pic.scaled(ui->image->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
    
            ui->image->setPixmap(scaledPic);
        }
    }
    
    
    void MainWindow::readTCPData()
    {
        if (!buffer.size())  // Pastikan buffer sudah diinisialisasi dengan ukuran yang tepat
            buffer.resize(bufferSize);
    
        QDataStream sendIn(tcpClient);
        sendIn.setVersion(QDataStream::Qt_5_0);
    
        // Penerimaan header hanya dilakukan sekali
        if (bytesReceived < sizeof(qint64) * 2) {
            if (tcpClient->bytesAvailable() >= sizeof(qint64) * 2) {
                sendIn >> totalBytes >> fileNameSize;
                bytesReceived += sizeof(qint64) * 2;
            }
        }
    
        // Penerimaan nama file hanya dilakukan sekali
        if (fileNameSize > 0 && fileName.isEmpty() && tcpClient->bytesAvailable() >= fileNameSize) {
            sendIn >> fileName;
    
            // Construct the new file path
            //QString filePath = "C:\\Fadli\\Kuliah\\Semester 6\\Reka\\4.QT\\coba\\" + fileName; //Deskop
            //QString filePath = "file:///storage/emulated/0/DCIM/Camera/IMG" + fileName; //HP
            QString filePath = "storage/emulated/0/Download/" + fileName; //AVD
            localFile = new QFile(filePath);
            if (!localFile->open(QFile::WriteOnly)) {
                qDebug() << "Cannot open file for writing";
                return;
            }
            ui->label->setText(tr(u8"Received %1 ...").arg(fileName));
            bytesReceived += fileNameSize;
            fileNameSize = 0;  // Reset agar tidak masuk ke kondisi ini lagi
        }
    
        // Membaca data yang tersisa dan menulis ke file
        while (tcpClient->bytesAvailable() > 0 && bytesReceived < totalBytes) {
            qint64 bytesToRead = qMin(tcpClient->bytesAvailable(), (qint64)buffer.size());
            qint64 bytesRead = tcpClient->read(buffer.data(), bytesToRead);
            if (bytesRead > 0) {
                localFile->write(buffer.data(), bytesRead);
                bytesReceived += bytesRead;
            }
        }
    
        // Update progress bar
        ui->progressBar->setMaximum(totalBytes);
        ui->progressBar->setValue(bytesReceived);
    
        // Selesaikan transfer file
        if (bytesReceived == totalBytes) {
            localFile->close();
            ui->label->setText(tr(u8"Successfully received file %1").arg(fileName));
            delete localFile;  // Penting untuk menghapus pointer
            localFile = nullptr;
            totalBytes = 0;
            bytesReceived = 0;
            fileName.clear();
        }
    }
    
    

    IDK why UDP cant Connected, and why TCP cant receive file
    a1bee67d-568d-4518-86b8-dded4ae80e1c-image.png
    and i trying with quick too with the same logic, its end up like this (fyi the file is not saved)
    1ce59a0c-5dbc-4b69-99c3-1d5a6d010cc2-image.png

    1 Reply Last reply
    0
    • piervalliP Offline
      piervalliP Offline
      piervalli
      wrote on 4 Jun 2024, 08:13 last edited by
      #2

      8081 is the classic port http, have you checked is it used for other application?

      P 1 Reply Last reply 4 Jun 2024, 09:01
      0
      • piervalliP piervalli
        4 Jun 2024, 08:13

        8081 is the classic port http, have you checked is it used for other application?

        P Offline
        P Offline
        Patar
        wrote on 4 Jun 2024, 09:01 last edited by Patar 6 Apr 2024, 09:02
        #3

        @piervalli how do you check it ? before i try with 6969 but its still the same, TCP connection is fine but cant receive file 100% so it cant transfered. but the UDP is basically doesnt connect or the client didnt receive it

        jsulmJ 1 Reply Last reply 4 Jun 2024, 10:40
        0
        • piervalliP Offline
          piervalliP Offline
          piervalli
          wrote on 4 Jun 2024, 09:23 last edited by
          #4

          8080 e 8081 are classic port on http, Usually I use a height number 34545 but lower of 65536. If you are on Windows you can try with "netstat -a | findstr 34545 ", it shows if the port is used.

          P 1 Reply Last reply 5 Jun 2024, 01:20
          0
          • P Patar
            4 Jun 2024, 09:01

            @piervalli how do you check it ? before i try with 6969 but its still the same, TCP connection is fine but cant receive file 100% so it cant transfered. but the UDP is basically doesnt connect or the client didnt receive it

            jsulmJ Offline
            jsulmJ Offline
            jsulm
            Lifetime Qt Champion
            wrote on 4 Jun 2024, 10:40 last edited by
            #5

            @Patar You should add error handling to your code to see what happens.
            For example connect a slot to https://doc.qt.io/qt-6/qabstractsocket.html#errorOccurred and print the error.

            https://forum.qt.io/topic/113070/qt-code-of-conduct

            1 Reply Last reply
            1
            • piervalliP piervalli
              4 Jun 2024, 09:23

              8080 e 8081 are classic port on http, Usually I use a height number 34545 but lower of 65536. If you are on Windows you can try with "netstat -a | findstr 34545 ", it shows if the port is used.

              P Offline
              P Offline
              Patar
              wrote on 5 Jun 2024, 01:20 last edited by Patar 6 May 2024, 01:21
              #6

              @piervalli i try with 7600 as TCP socket but yeah its still didnt want to receiving 100%, is there something like wireshark to know flow of data in Qt? or how do you linking qt with wireshark ? for UDP i will try to debug what the error as @jsulm said
              this is my screenshot with my smartphone with the apps, the connection is established
              c2099238-3306-4fc1-bcba-b8fcba0e0841-Screenshot_267.png

              1 Reply Last reply
              0
              • P Offline
                P Offline
                Patar
                wrote on 5 Jun 2024, 04:13 last edited by
                #7

                i really dont know what going on.
                i try to make message system so its not one way but two way with udp
                and voila the Android can send message to Server (deskop) but server cant message the android

                i just add these in client
                image.png

                and receive it in server
                image.png

                that basically a copy paste from server (first program one way, only server can send message)
                here is the result
                image.png
                image.png

                the TCP is still stuck at 99%

                1 Reply Last reply
                0
                • P Offline
                  P Offline
                  Patar
                  wrote on 5 Jun 2024, 04:30 last edited by Patar 6 May 2024, 07:35
                  #8

                  update
                  i make it pair to pair (IP) not broadcast and the communication UDP works
                  (still idk why pair to pair works but broadcast do not)

                  the problem now is the TCP why its stuck
                  @piervalli @jsulm any idea?

                  1 Reply Last reply
                  0

                  1/8

                  4 Jun 2024, 08:09

                  • Login

                  • Login or register to search.
                  1 out of 8
                  • First post
                    1/8
                    Last post
                  0
                  • Categories
                  • Recent
                  • Tags
                  • Popular
                  • Users
                  • Groups
                  • Search
                  • Get Qt Extensions
                  • Unsolved