Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QTcpSocket - Unreadable response from Java server



  • Greetings to all moderators and members and developers
    The problem is as follows:
    I've built a server and client in Java using java.net.ServerSocket and java.net.Socket classes.
    Now everything works fine with both server application and client application written in Java, but i built a client GUI application using C++ Qt using QTcpSocket class, and it sends the command to Java server, the server correctly recieve the incoming message from the client application and successfully process it and send results back to client application, the problem is that the client application seems to be recieving an empty or unreadable response, eventhough the server sends it correctly.
    Here's the Server application code (written in Java):

    ServerApp.java

    package app;
    
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class App {
        public static void main(String[] args) throws Exception {
            try (ServerSocket server = new ServerSocket(45012)) {
                while (true) {
                    try {
                        Socket client = server.accept();
                        Thread clientThread = new Thread(new ClientThread(client));
                        clientThread.start();
                    }
                    catch (Exception ex) {}
                }
            }
            catch (Exception ex) {
                System.out.println("Server failed to start");
            }
        }
    }
    

    ClientThread.java (I forgot to mention that the server is multithreaded):

    package app;
    
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.Socket;
    import java.time.LocalDateTime;
    
    class ClientThread implements Runnable {
        private Socket clientSocket;
    
        public ClientThread(Socket clientSocket) {
            this.clientSocket = clientSocket;
            System.out.println("Client: " + clientSocket.getInetAddress() + ":" + clientSocket.getPort() + " has connected at: " + LocalDateTime.now());
        }
    
        public void run() {
            try {
                InputStream is = clientSocket.getInputStream();
                OutputStream os = clientSocket.getOutputStream();
                byte[] bytes = new byte[256];
                if (is.read(bytes) == -1) {
                    clientSocket.close();
                }
                else {
                    String input = new String(bytes);
                    String result = ""; 
                    String command = input.split(" ")[0];
                    System.out.println("Command recieved: (" + input + ") from client: " + clientSocket.getInetAddress() + ":" + clientSocket.getPort() + " at: " + LocalDateTime.now());
                    double p1 = Double.parseDouble(input.split(" ")[1]);
                    double p2 = Double.parseDouble(input.split(" ")[2]);
                    String temp = "";
                    if (command.toLowerCase().contentEquals("add")) {
                        temp += (p1 + p2);
                    }
                    else if (command.toLowerCase().contentEquals("sub")) {
                        temp += (p1 - p2);
                    }
                    result += temp;
                    System.out.println("Sending result: (" + result + ") to client : " + clientSocket.getInetAddress() + ":" + clientSocket.getPort() + " at: " + LocalDateTime.now());
                    os.write(result.getBytes());
                    os.flush();
                }
            }
            catch (Exception e) {}
            finally {
                try {
                    clientSocket.close();
                }
                catch (Exception ex) {}
            }
        }
    }
    

    Here's the Client application (written in Java) :

    package app;
    
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.Socket;
    import java.util.Scanner;
    
    public class App {
        public static void main(String[] args) throws Exception {
            Socket client = new Socket("127.0.0.1", 45012);
            InputStream is = client.getInputStream();
            OutputStream os = client.getOutputStream();
            Scanner in = new Scanner(System.in);
            byte[] message = new byte[256];
            while (true) {
                String input = in.nextLine();
                if (input.contentEquals("exit")) {
                    break;
                }
                os.write(input.getBytes());
                os.flush();
                
                is.read(message);
                System.out.println(new String(message));
            }
    
            is.close();
            os.close();
            in.close();
            client.close();
        }
    }
    

    Here's the ** Client application** (written in C++ Qt ):

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    
    #include <QMessageBox>
    #include <QtNetwork/QTcpSocket>
    
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
    }
    
    MainWindow::~MainWindow()
    {
        delete ui;
    }
    
    void MainWindow::on_pushButton_clicked()
    {
        QTcpSocket *socket = new QTcpSocket();
        socket->connectToHost("localhost", 45012);
        QString command = "";
        QMessageBox *msgbox = new QMessageBox();
        command += ui->comboBox->currentText();
        command += " ";
        command += ui->lineEdit->text();
        command += " ";
        command += ui->lineEdit_2->text();
        socket->write(command.toAscii());
        ui->textEdit->append(command);
        QString result = QString(socket->readAll());    // Empty or unreadable response
        msgbox->setText(result);
        msgbox->show();
    }
    
    

  • Lifetime Qt Champion

    All Qt network stuff is asynchronous. Please read the documentation and use signals/slots to retrieve the data.



  • @Syrian-Lucianos as @Christian-Ehrlicher suggested, you may need to work with signal & slots. You may want to review this example for instance, and check how/when the QTcpSocket.readAll() method is actually used.


Log in to reply