Right now I have a console client which communicates with the server via ObjectInputStream.readObject()
and ObjectOutputStream.writeObject()
. For a console based application, this seems to work as is.
The problem is that the class which has the i/o streams also has a reference to the System.console()
object!
How can I refactor this class so that it's more generalized? I would almost want to treat the connection as a utility, or, perhaps, as a bean, which would then get passed to, for example, a Swing GUI, or, perhaps, a system console.
package net.bounceme.dur.client;
import net.bounceme.dur.data.Title;
import java.net.*;
import java.io.*;
import java.util.Arrays;
import java.util.logging.Logger;
import net.bounceme.dur.data.State;
public class Client {
private static final Logger log = Logger.getLogger(Client.class.getName());
private String server = "localhost";
private int portNumber = 8080;
private final Console c = System.console();
private Client() {
}
public Client(String server, int portNumber) {
this.server = server;
this.portNumber = portNumber;
}
public void inputOutput() throws IOException, ClassNotFoundException {
Socket socket = new Socket(server, portNumber);
boolean eof = false;
Title title = null;
State state = State.undefined;
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream())) {
do {
try {
title = (Title) objectInputStream.readObject();
log.info(title.toString());
do {
state = State.undefined;
try {
c.printf("enter the state for record:");
state = State.valueOf(c.readLine());
} catch (java.lang.IllegalArgumentException iae) {
log.warning(Arrays.deepToString(State.values()));
}
} while (state == State.undefined);
title.setState(state);
title.setTitle("modified from client");
objectOutputStream.writeObject(title);
} catch (java.io.EOFException eofe) {
eof = true;
}
} while (!eof);
}
}
}
see also: