import java.io.*; import java.net.*; /** * Example of how to make a very simple java server. * Run this as: java ServerListen <port> * * The server binds to a port, and accepts connection. * It prints out what each client sends, and then * closes the connection without responding. * * @author Rimon Barr * @version 1.0, 02/11/99 */ public class ServerListen { public static void main(String args[]) { try { // decode port number from command line int port=Integer.valueOf(args[0]).intValue(); // create server socket on that port ServerSocket ss=new ServerSocket(port); // process connections forever while (true) { System.out.println("Listening on port "+port); // listen for incoming connections Socket s=ss.accept(); // process connection (no thread used here, // but usually we use a thread, because processing // may take a long time) dump(s.getInputStream(), System.out); // close the socket, because it could be a while // before the next connection comes in (plus // we don't want to wait for garbage collection, // therefore s=null is not sufficient) s.close(); s=null; } } catch (NumberFormatException e) { System.err.println("Invalid port number: "+args[0]); } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Must pass in a port number"); } catch (IOException e) { System.err.println(e); } } /** * Dump one stream into another * @param i input stream * @param o output stream * @exception IOException thrown if either the input or output * streams have an error */ public static void dump(InputStream i, OutputStream o) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(i)); PrintWriter out = new PrintWriter(o); String l = in.readLine(); while(l!=null) { out.println(l); l=in.readLine(); } } }