rcrd18
rcrd18

Reputation: 3

Client can't send second execution to server

I have a server-client program in Java. The server do some basic calculations and send the result to the client. Before that the client has to send the operation and the values. I can run sucessfully one time, but when I insert second operation and values I get null has a result. Why this happens?

Server

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

private static final int PORT = 9001;

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    System.out.println("O servidor está a correr...");
    ServerSocket listener = new ServerSocket(PORT);
    listener.setSoTimeout(0);
    try{
        while(true){
            new Handler(listener.accept()).start();
        }
    }finally{
        listener.close();
        System.out.println("Servidor fechou!");
    }
}

private static class Handler extends Thread{
    private Socket socket;
    private BufferedReader in;
    private PrintWriter out;

    public Handler(Socket socket){
        this.socket = socket;
    }

    public void run(){
        try{
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            while(true){
                String line = in.readLine();
                System.out.print(line);
                double result = parseExecution(line);
                out.write("" + result + "\n");
                out.close();
                in.close();
            }
        }catch(IOException e){
            e.printStackTrace();
        }
        out.flush();


    }

    private double parseExecution(String line) throws IllegalArgumentException{
        // TODO Auto-generated method stub
                double result = 0;
                String [] elements = line.split(":");
                if (elements.length != 3){
                    throw new IllegalArgumentException("parsing error!");
                }
                double firstValue = 0;
                double secondValue = 0;
                try{
                    firstValue = Double.parseDouble(elements[1]);
                    secondValue = Double.parseDouble(elements[2]);
                } catch(Exception e){
                    throw new IllegalArgumentException("Invalid arguments!");
                }
            switch (elements[0].charAt(0)) {
            case '+':
                result = firstValue + secondValue;
                break;
            case '-':
                result = firstValue - secondValue;
                break;
            case '*':
                result = firstValue * secondValue;
                break;
            case '/':
                if(secondValue != 0)
                result = firstValue / secondValue;
                break;
            default: 
                throw new IllegalArgumentException("Invalid math operation!");
            }
            return result;
        }
}
}

Client

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JOptionPane;
import javax.xml.bind.helpers.ParseConversionEventImpl;

public class MathClient {

private String getServerAddress(){
    return JOptionPane.showInputDialog("Introduza IP do Servidor", JOptionPane.QUESTION_MESSAGE);
}

private void run() throws IOException {
    String serverAddress = getServerAddress();
    int port = 9001;

    // criar a socket

    Socket socket = new Socket(serverAddress, port);
    BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    BufferedReader op = new BufferedReader(new InputStreamReader(System.in));
    BufferedReader valor1 = new BufferedReader(new InputStreamReader(System.in));
    BufferedReader valor2 = new BufferedReader(new InputStreamReader(System.in));
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    while(true){
        System.out.println("Operação(+,-,*,/): ");
        String operacao = op.readLine();
        System.out.println("Primeiro valor: ");
        String primeiroValor = valor1.readLine();
        System.out.println("Segundo valor: ");
        String segundoValor = valor2.readLine();
        writer.write(operacao+":"+primeiroValor+":"+segundoValor);
        writer.newLine();
        writer.flush();
        //double resultado = Double.parseDouble(reader.readLine());
        System.out.println(reader.readLine());

    }

}

public static void main(String[] args) throws UnknownHostException, IOException {
    MathClient client = new MathClient();
    client.run();
}

}

Thanks!

EDIT: Inside the run() method I'm doing a while cycle. But now I'm getting an error saying Stream Closed. When I tried to put in.close() outside the while cycle it gives me another error and to remove the in.close().

java.io.IOException: Stream closed
at java.io.BufferedReader.ensureOpen(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at MathFinal.Server$Handler.run(Server.java:41)

Line 41 is: String line = in.readLine();

Upvotes: 0

Views: 70

Answers (1)

Humberto Pinheiro
Humberto Pinheiro

Reputation: 1174

I fixed your code and it's working using Java 7 try-with-resources. Here is the significant snippet:

private static class Handler extends Thread{
    private Socket socket;

    public Handler(Socket socket){
        this.socket = socket;
    }

    public void run(){
        try(BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
            while(true){
                String line = in.readLine();
                System.out.print(line);
                double result = parseExecution(line);
                out.write("" + result + "\n");
                out.flush();
            }
        }catch(IOException e){
            e.printStackTrace();
        }

    }

Doing this way you don't need to worry about closing the resources yourself.

Upvotes: 1

Related Questions