import java.io.*; import java.net.Socket; import java.util.Date; public class Monitor { public static void main(String[] args) { try { new Monitor(); } catch (Exception e) { fatal(e); } } private static synchronized void fatal(Throwable e) { try { PrintWriter out = new PrintWriter(new FileWriter("Monitor.dump", /*append=*/ true)); try { out.write("Exception in "); out.write(Thread.currentThread().getName()); out.write(" thread at "); out.write(new Date().toString()); out.write("\r\n"); e.printStackTrace(out); } finally { out.close(); } } catch (IOException f) { } System.exit(1); } private Process fProc; private Socket fRemote; private InputStream fRemoteIn; private OutputStream fRemoteOut; private int fThreadCount; Monitor() throws IOException { fRemote = new Socket("localhost", Server.PORT); fRemoteIn = fRemote.getInputStream(); fRemoteOut = fRemote.getOutputStream(); fProc = Runtime.getRuntime().exec("GNUChess"); fThreadCount = 2; new WatchThread(System.in, fProc.getOutputStream(), true); new WatchThread(fProc.getInputStream(), System.out, false); } synchronized void send(byte[] buffer, int length) throws IOException { fRemoteOut.write(buffer, 0, length); fRemoteOut.flush(); fRemoteIn.read(); } synchronized void threadDone() { fThreadCount--; if (fThreadCount == 0) { try { fRemote.close(); } catch (IOException e) { } } } class WatchThread extends Thread { private InputStream fIn; private OutputStream fOut; private byte[] fBuffer = new byte[128]; private int fLength = 0; private String fLine; protected WatchThread(InputStream in, OutputStream out, boolean toEngine) { super(toEngine ? "ToEngine" : "FromEngine"); fIn = in; fOut = out; fBuffer[0] = (byte) (toEngine ? '>' : '<'); fLength = 1; start(); } public void run() { try { while(true) { int ch = fIn.read(); if (ch == -1) break; if (ch == '\r') continue; fBuffer[fLength++] = (byte) ch; if (ch == '\n') { send(fBuffer, fLength); fOut.write(fBuffer, 1, fLength-1); fOut.flush(); fLength = 1; } } threadDone(); } catch(Exception e) { fatal(e); } } } }