package clientserver; import java.io.*; import java.net.*; public abstract class Communicator { ObjectOutputStream oos; // constructor sends a header (software version) ObjectInputStream ois; // constructor receive the header (check for compatibility) protected Communicator(String hostAddress, int portNumber) throws UnknownHostException, IOException { this(new Socket(hostAddress, portNumber)); } protected Communicator(Socket s) throws IOException { oos = new ObjectOutputStream(s.getOutputStream()); ois = new ObjectInputStream(s.getInputStream()); } public void start() { startActiveProcessing(); startReceiving(); } void startActiveProcessing() { if (this instanceof Runnable) ((new Thread((Runnable) this))).start(); } protected void startReceiving() { // support reactive clients (new Thread() { public void run() { try { while (true) messageReceived(receive()); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }).start(); } abstract void messageReceived(M message); M receive() throws IOException, ClassNotFoundException { // active client calls this to wait for the next message return (M) ois.readObject(); } protected void send(M message) { try { oos.writeObject(message); } catch (IOException e) { throw new RuntimeException("send failed due to " + e, e); } } }