import java.net.*; import java.io.*; import java.util.zip.*; public class Echo { // java -client servername port // java -server port public static void main(String[] args) throws Throwable { if ("-client".equals(args[0])) { SocketIO sio = new SocketIO(new Socket(args[1], Integer.parseInt(args[2]))); try { String ln; Console con = System.console(); while((ln = sio.read()) != null) { con.format("ECHO: %s", ln); ln = con.readLine("%nMe : "); if(ln != null) sio.write(ln); if("exit".equals(ln)) break; } } catch (IOException ioe) { ioe.printStackTrace(); } finally { sio.close(); } } else if ("-server".equals(args[0])) { ServerSocket ss = new ServerSocket(Integer.parseInt(args[1])); while(true) { new SSThread(ss.accept()).start(); } } } /** * Wraps a connected Socket object. It then can be used to read bytes * from/write bytes into the underlying socket streams. */ private static class SocketIO { private Socket s; private OutputStream os; private InputStream is; SocketIO(Socket s) throws IOException { this.s = s; this.os = s.getOutputStream(); this.is = s.getInputStream(); } byte[] bb = new byte[1024]; String read() throws IOException { int n = is.read(bb); return new String(bb, 0, n); } void write(String ln) throws IOException { os.write(ln.getBytes()); os.flush(); } void close() { try { s.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } /** * A worker Thread that wraps a Socket object returned from ServerSocket.accept() * and echos every byte read from client. */ static class SSThread extends Thread { private SocketIO sio; public SSThread(Socket s) throws IOException { this.sio = new SocketIO(s); } public void run() { try { sio.write("Welcome to ECHO!"); String ln; while((ln = sio.read()) != null) { sio.write(ln); if("exit".equals(ln)) break; } } catch (IOException ioe) { ioe.printStackTrace(); } finally { sio.close(); } } } }