0

I am trying to send messages between two JVMs: a server starts a second process. The second process is then to send a message to the server which prints the message to the console. The code is as follows:

public class Server
{
    public static void main(String[] args)
    {
        Process client=null;
        BufferedReader clientInput=null;

        try
        {
            client=Runtime.getRuntime().exec("java Client");
            clientInput=new BufferedReader(new InputStreamReader(client.getInputStream()));
        }
        catch(IOException e){}

        System.out.println("Waiting for the client to connect...");

        try
        {
            String msg=clientInput.readLine();
            System.out.println(msg);
        }
        catch(IOException e){}

        client.destroy();
    }
}

and

public class Client 
{
    public static void main(String[] args) 
    {   
        BufferedWriter out = new BufferedWriter( new OutputStreamWriter(System.out));

        try 
        {
            out.write("Ready\n");
            out.flush();
        } 
        catch (Exception e){}
    }
}

If I run this, I get as output from the server null. In the end, the communication should be both ways. Any help greatly appreciated.

EDIT: I don't get any errors (just removed the print statements from the catch blocks to save space).

2 Answers 2

1

I think you need to add a while loop:

while ((s = in.readLine()) != null && s.length() != 0)
    System.out.println(s);
}
Sign up to request clarification or add additional context in comments.

Comments

1

You receive null at the end of the stream. The client correctly starts, sends Ready, and the the ends, so the stream ends.

Totally correct behaviour. If the client would end itself (but instead do something else like reading server messages on stdin), the server would never receive a null.

Edit: NEVER EVER (!!!!!) do this:

catch(IOException e){}

At least write:

catch(IOException e){ e.printStackTrace() }

This will show you your error!

In my company, this is one of the elementary rules of code style!

2 Comments

The problem is that all I receive is null - the "Ready" is never received though.
I have the e.printStackTrace() in my code. As I said above, I just removed it so not to clutter up too much space. As I said, no exceptions are thrown.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.