Calculator using Java Socket

Asked

Viewed 4,105 times

2

I’m doing a job at the college and I took some information from the Internet, the professor asked a client to submit 2 values and a basic operation, the server should take this and return the total. It turns out that the client only takes the variables itself, does not take the total that comes from the server and nor the opr which is the symbol of the operation.

public class Servidor2 {

    public static void main(String[] args) throws IOException {

        int num1, num2, total = 0;
        int operacao = 0;
        char opr = 0;

        //Cria um socket na porta 12342
        ServerSocket servidor = new ServerSocket(12342);
        System.out.println("Porta 12342 aberta!");

        // Aguarda alguém se conectar. A execução do servidor
        // fica bloqueada na chamada do método accept da classe
        // ServerSocket. Quando alguém se conectar ao servidor, o
        // método desbloqueia e retorna com um objeto da classe
        // Socket, que é uma porta da comunicação.

        System.out.print("Aguardando conexão do cliente...");
        Socket cliente = servidor.accept();

        System.out.println("Nova conexao com o cliente " + cliente.getInetAddress().getHostAddress());


        ObjectOutputStream resultado = new ObjectOutputStream(cliente.getOutputStream());
        ObjectInputStream dados = new ObjectInputStream(cliente.getInputStream());

        num1 = dados.readInt();
        num2 = dados.readInt();

        operacao = dados.readInt();
        if (operacao == 1) {

            opr = '+';
            total = (num1 + num2);


        }
        if (operacao == 2) {

            opr = '-';
            total = (num1 - num2);
        }
        if (operacao == 3) {


            opr = 'x';
            total = (num1 * num2);
        }
        if (operacao == 4) {


            opr = '/';
            total = (num1 / num2);
        } else {


            System.out.printf("Você digitou uma operação inválida.");

        }

        resultado.writeInt(total);
        resultado.writeChar(opr);
        resultado.flush();
        resultado.flush();
        servidor.close();
    }
}


public class Cliente2 {

    public static void main(String[] args) throws UnknownHostException, IOException {
        int num1 = 0;
        int num2 = 0;
        int operacao = 0;
        char opr;
        Socket cliente = new Socket("127.0.0.1", 12342);
        System.out.println("O cliente conectou ao servidor");


        ObjectInputStream resultado = new ObjectInputStream(cliente.getInputStream());
        ObjectOutputStream dados = new ObjectOutputStream(cliente.getOutputStream());


        num1 = Integer.parseInt(JOptionPane.showInputDialog("Digite o primeiro número"));
        num2 = Integer.parseInt(JOptionPane.showInputDialog("Digite o segundo número"));
        operacao = Integer.parseInt(JOptionPane.showInputDialog("Qual operação desejada? 1= +, 2= -,3= X,4= / "));
        dados.writeInt(operacao);
        dados.writeDouble(num1);
        dados.writeDouble(num2);

        dados.flush();

        int total = resultado.readInt();
        opr = resultado.readChar();
        System.out.println("Total de " + num1 + opr + num2 + " = " + total);

        cliente.close();
    }
}
  • See the [tour], if you think the main objective of this question has been achieved you can accept the answer. You can also vote for everything on the site you find useful, not just things related to your posts.

1 answer

1

The problem in your code is time to send and receive the data, in the client you are using:

dados.writeInt(operacao);
dados.writeDouble(num1);
dados.writeDouble(num2);

And on the server:

num1 = dados.readInt();
num2 = dados.readInt();
operacao = dados.readInt();

Two problems are noticed here, the first would be the fact that you are sending a Double and want to receive a Integer, and the other would be the order that the data are sent and received, because in the customer you send operacao, num1 and num2, and on the server you are receiving num1, num2 and operacao, the fact that the variables have the same name means nothing in this case.

To solve your problem, adjust the two classes with Integer or with Double and put the same shipping and receiving order, I will post as would be using Double.

public class Servidor2 {

    public static void main(String[] args) throws IOException {

        double num1, num2, total = 0.0;
        int operacao;
        char opr = '\n';

        //Cria um socket na porta 12342
        ServerSocket servidor = new ServerSocket(12342);
        System.out.println("Porta 12342 aberta!");

        // Aguarda alguém se conectar. A execução do servidor
        // fica bloqueada na chamada do método accept da classe
        // ServerSocket. Quando alguém se conectar ao servidor, o
        // método desbloqueia e retorna com um objeto da classe
        // Socket, que é uma porta da comunicação.

        System.out.print("Aguardando conexão do cliente...");
        Socket cliente = servidor.accept();

        System.out.println("Nova conexao com o cliente " + cliente.getInetAddress().getHostAddress());


        ObjectOutputStream resultado = new ObjectOutputStream(cliente.getOutputStream());
        ObjectInputStream dados = new ObjectInputStream(cliente.getInputStream());

        operacao = dados.readInt();
        num1 = dados.readDouble();
        num2 = dados.readDouble();

        if (operacao == 1) {

            opr = '+';
            total = (num1 + num2);

        } else if (operacao == 2) {

            opr = '-';
            total = (num1 - num2);

        } else if (operacao == 3) {

            opr = 'x';
            total = (num1 * num2);

        } else {

            opr = '/';
            total = (num1 / num2);

        }

        resultado.writeDouble(total);
        resultado.writeChar(opr);
        resultado.flush();

        resultado.close();
        dados.close();
        servidor.close();
    }
}

Note: in this case you can use if and else if instead of just if, this avoids unnecessary checks depending on the value of opr.

Note 2: the validation of the operation is easier to be done directly in the client.

Note 3: it is not necessary to use resultado.flush(); twice.

public class Cliente2 {

    public static void main(String[] args) throws UnknownHostException, IOException {
        double num1;
        double num2;
        int operacao = 0;
        char opr;
        Socket cliente = new Socket("127.0.0.1", 12342);
        System.out.println("O cliente conectou ao servidor");


        ObjectInputStream resultado = new ObjectInputStream(cliente.getInputStream());
        ObjectOutputStream dados = new ObjectOutputStream(cliente.getOutputStream());


        num1 = Double.parseDouble(JOptionPane.showInputDialog("Digite o primeiro número"));
        num2 = Double.parseDouble(JOptionPane.showInputDialog("Digite o segundo número"));
        while (!((operacao >= 1) && (operacao <= 4))) {
            operacao = Integer.parseInt(JOptionPane.showInputDialog("Qual operação desejada? 1= +, 2= -,3= X,4= / "));
            if (!((operacao >= 1) && (operacao <= 4))) {
                System.out.println("Você digitou uma operação inválida.");
            }
        }
        dados.writeInt(operacao);
        dados.writeDouble(num1);
        dados.writeDouble(num2);
        dados.flush();

        double total = resultado.readDouble();
        opr = resultado.readChar();
        System.out.println("Total de " + num1 + opr + num2 + " = " + total);

        resultado.close();
        dados.close();
        cliente.close();
    }
}

Note: the validation made consists of a loop that checks whether the operation typed is in 1 and 4, if not, prints in the console and requests again the operation for the user.

  • Matthew, I made the changes you said, but it still doesn’t work the operations, it returns the numbers typed, but it doesn’t do the operation and it doesn’t return the symbol of the operation, I believe it’s not taking the data returned by the server, I don’t know how to debug it, I’ve been catching it since too early today to do it.

  • do you get any error? I tested with the following entry 40, 2 and 4, the result was O cliente conectou ao servidor Total de 40.0/2.0 = 20.0, which IDE you are using?

  • Matthew, I’m using Eclipse Luna, I don’t get any error, it returns it to me on the console 'The client connected to the server Total of 40.0 20.0 = 0.0'

  • take a look at the class Servidor2, you corrected the order to operacao = dados.readInt(); num1 = dados.readInt(); num2 = dados.readInt();?

  • Matthew really was what was wrong, I really appreciate the help. Now I have another question to break my head.About threads, 2 users connecting.

  • @brenoguto, do you really need to work with threads? Make a while in class Servidor2 to keep receiving customers would not serve you?

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.