import java.io.*; import java.net.*; public class EchoClient { public static void main(String[] args) throws IOException { if (args.length != 2) { System.err.println( "Usage: java EchoClient "); System.exit(1); } String hostName = args[0]; int portNumber = Integer.parseInt(args[1]); InetSocketAddress socketAddress = new InetSocketAddress(hostName, portNumber); try ( Socket echoSocket = new Socket(); BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); ) { echoSocket.connect(socketAddress); System.out.println("Connected to "+echoSocket.getInetAddress().toString()+":"+echoSocket.getPort()); try ( PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader(echoSocket.getInputStream() )); ) { String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echoed: "+in.readLine()); } } // no catch } catch (UnknownHostException e) { System.err.println("Don't know about host " + hostName); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to " + hostName); System.exit(1); } } }