Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. QTcpSocket - Unreadable response from Java server
Forum Updated to NodeBB v4.3 + New Features

QTcpSocket - Unreadable response from Java server

Scheduled Pinned Locked Moved Unsolved General and Desktop
3 Posts 3 Posters 245 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.
  • S Offline
    S Offline
    Syrian Lucianos
    wrote on 2 Apr 2020, 02:33 last edited by
    #1

    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();
    }
    
    
    P 1 Reply Last reply 3 Apr 2020, 14:54
    0
    • C Offline
      C Offline
      Christian Ehrlicher
      Lifetime Qt Champion
      wrote on 2 Apr 2020, 04:18 last edited by
      #2

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

      Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
      Visit the Qt Academy at https://academy.qt.io/catalog

      1 Reply Last reply
      2
      • S Syrian Lucianos
        2 Apr 2020, 02:33

        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();
        }
        
        
        P Offline
        P Offline
        Pablo J. Rogina
        wrote on 3 Apr 2020, 14:54 last edited by
        #3

        @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.

        Upvote the answer(s) that helped you solve the issue
        Use "Topic Tools" button to mark your post as Solved
        Add screenshots via postimage.org
        Don't ask support requests via chat/PM. Please use the forum so others can benefit from the solution in the future

        1 Reply Last reply
        0

        1/3

        2 Apr 2020, 02:33

        • Login

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