// introduction to client sockets in Java, by Narendra Singhal and // Norman Matloff; paired with Svr.java // usage: java Clnt remotehost command // where command is w or ps // sends the command to remotehost, which runs it there and sends us // back the output of the command // note: at the bottom level, there are still the standard system // calls, e.g. socket(), connect(), bind(), etc.; the difference is that // in Java they are made by the underlying JVM, rather than by the // programmer him/herself import java.lang.*; import java.io.*; import java.net.*; public class Clnt { private static final int Port = 3000; private static Socket Sock = null; public static void main (String Args[]) { try { try { // class Socket is for TCP (use class DatagramSocket for // UDP); note that the "connect" action is included in the // operations done in invoking the constructor Sock = new Socket(Args[0],Port); } // Socket() throws UnknownHostException, IOException catch (UnknownHostException E) { System.out.println(E+": check remote host address"); System.exit(1); } catch(IOException E) { System.out.println(E+": some other socket/connect problem"); System.exit(1); } InputStream Input = Sock.getInputStream(); OutputStream Output = Sock.getOutputStream(); // getInputStream() and getOutputStream() return pointers to // the types InputStream and OutputStream, respectively; // we'll just use these as is, without chaining to more // efficient buffered I/O classes // send the command to the remotehost for (int I = 0; I < Args[1].length(); I++) Output.write(Args[1].charAt(I)); // read the response from the remote host, and print it out // on the screen; we'll build up lines byte-by-byte, though it // could be done more compactly if we used more advanced // machinery, such as BufferedReader.readLine() int ByteFromServer; String Line = ""; while (true) { ByteFromServer = Input.read(); if (ByteFromServer == '\n') { if (Line.equals("end")) System.exit(1); System.out.println(Line); Line = ""; } else Line = Line + (char) ByteFromServer; } } // catch exceptions which may arise during Input.read() catch(IOException E) { System.out.println(E+": broken connection with server"); System.exit(1); } } }