// introduction to server sockets in Java, by Narendra Singhal and // Norm Matloff; paired with Clnt.java // usage: java Svr // accepts a command w or ps from the client, runs the command on the // local machine, and then sends the command's output back to the // client, which displays it there // 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 Svr { private static final int Port = 3000; private static ServerSocket SvrSock = null; public static void main(String[] Args) { // have special class, ServerSocket, for server sockets; // constructor's actions include includes "bind" operation try { SvrSock = new ServerSocket(Port); } catch(Exception E) { System.out.println( "couldn't create server socket; " + E); System.exit(1); } System.out.println("server is up "); while (true) ProcessACall(); } public static void ProcessACall() { System.out.println("waiting for client connection"); try { // when accept() gets a "phone call" from the client, it // sets up an ordinary socket (see comments on Socket class // in Clnt.java) Socket TmpSock = SvrSock.accept(); System.out.println("connection from client"); InputStream Input = TmpSock.getInputStream(); OutputStream Output = TmpSock.getOutputStream(); // read command from the client int ClntByte = Input.read(); String Cmd; if (ClntByte == 'w') Cmd = "w"; else Cmd = "ps"; try { // set up a non-Java process running Cmd on the // native machine (i.e. not on the JVM); throws IOException Process Prcs = Runtime.getRuntime().exec(Cmd); // get the output from the command InputStream In = Prcs.getInputStream(); byte CmdOut[]; CmdOut = new byte[1000]; int CmdOutLength = In.read(CmdOut); // send that output and a "homemade" EOF to the client CmdOut[CmdOutLength] = '\n'; CmdOut[CmdOutLength+1] = 'e'; CmdOut[CmdOutLength+2] = 'n'; CmdOut[CmdOutLength+3] = 'd'; CmdOut[CmdOutLength+4] = '\n'; Output.write(CmdOut); } catch(IOException E) { System.out.println("" + E); } } catch (Exception E) { System.out.println("connection to current client broken"); } } }