In this example, the client connects to the server and the server returns a "canned" message and breaks the connection. Thus, the client and server programs function at the "Hello, World!" level.
The important functionality of this server is located in the
runServer
method. A minimal user interface is created in the constructor, and the program is driven from themain
method.import java.net.*; import java.io.*; import java.util.*; import java.awt.*; import java.awt.event.*; public class Server_Basic extends Frame implements WindowListener{ ServerSocket listenSocket; Socket connection; OutputStream outStream; DataOutputStream outDataStream; TextArea logDisplay; String message; public Server_Basic () { super ( "Server_Basic" ); logDisplay = new TextArea ( 40, 10 ); add ( "Center", logDisplay ); addWindowListener ( this ); resize ( 400, 300 ); show (); } // end Server_Basic constructor // ************** public void runServer ( ) { try { listenSocket = new ServerSocket ( 8901 ); logDisplay.setText ( "Server started " ); try { InetAddress here = InetAddress.getLocalHost (); String host = here.getHostName (); logDisplay.appendText ( "on "+host+", port 8901\n" ); } catch (UnknownHostException e) { logDisplay.setText ( "Problem with local host\n" ); } connection = listenSocket.accept (); logDisplay.appendText ( "Connection request received\n" ); outStream = connection.getOutputStream (); outDataStream = new DataOutputStream ( outStream ); message = new String ( "Hello, Client, from Server!" ); outDataStream.writeUTF ( message ); logDisplay.appendText ( "Text sent to client: \n" ); logDisplay.appendText ( " "+message+"\n" ); logDisplay.appendText ( "Closing socket\n" ); connection.close (); } // end try catch ( IOException except) { except.printStackTrace (); } // end catch } // end runServer // ************** public static void main ( String [ ] args ) { Server_Basic server = new Server_Basic (); server.runServer (); } // end main //*********** Utility Methods *********** //*********** Interface Methods *********** //**** WindowListener methods public void windowActivated ( WindowEvent e ) { } public void windowDeactivated ( WindowEvent e ) { } public void windowOpened ( WindowEvent e ) { } public void windowClosed ( WindowEvent e ) { } public void windowClosing ( WindowEvent e ) { this.hide (); this.dispose (); System.exit(0); } public void windowIconified ( WindowEvent e ) { } public void windowDeiconified ( WindowEvent e ) { } } // end Server_Basic