This server is identical to the mid-size server, discussed above, except that it has no user interface. Consequently, it can be run on a remote UNIX host through telnet. It runs on port 8901 by default; however, you may specify an alternative port through a command line argument. You can find a copy of the program in the
programdirectory for this lesson.import java.net.*; import java.io.*; import java.util.*; import java.awt.*; import java.awt.event.*; public class Server_Second_NI { //**************** single-threaded server, with UI ServerSocket listenSocket; Socket connection; InputStream inStream; DataInputStream inDataStream; OutputStream outStream; DataOutputStream outDataStream; String message; public static final int DEFAULT_PORT = 8901; int port; public Server_Second_NI () { super (); } // end Server_Second constructor // ************** Primary Listen & Respond Method public void connectClient ( ) { try { listenSocket = new ServerSocket ( port ); System.out.println ( "Server running on "+" port "+port+"\n" ); connection = listenSocket.accept (); outStream = connection.getOutputStream (); outDataStream = new DataOutputStream ( outStream ); inStream = connection.getInputStream (); inDataStream = new DataInputStream ( inStream ); System.out.println ( "Connection request received\n" ); System.out.println ( "Message received:\n" ); try { message = inDataStream.readUTF (); System.out.println ( message +"\n"); } // end try for input catch ( EOFException except ) { System.out.println ( "message EOF received\n" ); } // end catch catch ( IOException except ) { System.out.println ( "IO Exception raised" ); except.printStackTrace (); } // end catch outDataStream.writeUTF ( message ); System.out.println ( "Message sent:\n" ); System.out.println ( message +"\n"); System.out.println ( "Connection closed\n" ); connection.close (); return; } // end try catch ( IOException except) { except.printStackTrace (); } // end catch } // end connectClient // ************** public static void main ( String [ ] args ) { Server_Second_NI server = new Server_Second_NI (); if ( args.length > 0 ) server.port = Integer.parseInt ( args[0] ); else server.port = DEFAULT_PORT; server.connectClient(); } // end main } // end Server_Second_NI