Error TCP and UDP
-
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 serverMainWindow::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
and i trying with quick too with the same logic, its end up like this (fyi the file is not saved)
-
@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
-
@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
@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. -
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.
@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
-
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 androidi just add these in client
and receive it in server
that basically a copy paste from server (first program one way, only server can send message)
here is the result
the TCP is still stuck at 99%