// Copyright © 2002 // John M. Thompson // Boulder, Colorado USA // jt@iwaypublishing.com // http://www.iwaypublishing.com // // A limited right to copy this page for // individual (non-commercial) educational // use only is hereby granted. import java.net.ServerSocket; import java.net.Socket; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; public class server { public static final int PORT = 1789; public static final String greeting = "Hello, Client. Nice to meet you!"; /** * Run server first, then in separate cmd shell, run client. *

* Usage (Windows): > java -classpath . server * * @param args Array of parameters passed to the application * via the command line. */ public static void main( String[] args ) throws IOException, InterruptedException { // Create a server socket to listen for connections java.net.ServerSocket server = new ServerSocket( PORT ); System.out.println( "Server awaiting connection -\n" ); // Blocks until client request, then creates new // socket on which to conduct client conversation. java.net.Socket client = server.accept(); System.out.println( "Server received connection.\n" ); java.io.InputStream in = client.getInputStream(); java.io.OutputStream out = client.getOutputStream(); byte[] inputStringBytes = new byte[ 256 ]; int inputLen = in.read( inputStringBytes ); System.out.println( "Server received: " + new String( inputStringBytes, 0, inputLen ) + "\n" ); System.out.println( "Server sending: " + greeting + "\n" ); out.write( greeting.getBytes() ); out.flush(); in.close(); out.close(); client.close(); server.close(); System.out.println( "\nServer done." ); System.out.println( "Press " ); byte[] response = new byte[256]; System.in.read( response ); } }