Question

I am currently working on a simple client/server application that takes in a single input from the command line. Valid inputs are either an integer or an 'r'. If an integer is inputted, the server is supposed to add and output the value of that integer to all previous integer inputs. If an 'r' is inputted, the server is supposed to reset the output value to 0.

On the client side, I got the following code to pass the different input types to the server:

if (args[0].equalsIgnoreCase("r")) { 
    out.write("reset".getBytes());
} else {
    out.write(i); //i is an integer that was converted from args[0] using Integer.parseInt()
}

However, on the server side, I would like to determine the type of input that it gets from the client. Specifically, is there any way to make the server check if it is receiving an integer or a byte array from the client?

Was it helpful?

Solution

My suggestion is to use an ObjectStream, to output the variable or the integer. You can use the readObject() method on the ObjectInputStream to read an object, and use getClass or instanceOf to determine what it's an instance of.

For example: Object o = objectInputStream.readObject(); if (o instanceof String) { System.out.println("It's a string!"); } else if(o instanceof Integer) { System.out.println("It's an integer"); }

Note that you might need to send an Integer as opposed to int. If you send an int, then using the readInt() method would read an int, but since you don't know if the next thing you're getting is an int or String, you can't really do that.

What I've done before in this case is to send a known thing, followed by the unknown. For example, an enum or string that explains what the next thing is. So you could send "S" for String or "I" for int. That's probably a lot more difficult then just saying out.writeObject(Integer.valueOf(i))

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top