// 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.Socket; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; public class client { /** * Run server first, then in separate cmd shell, run client. *

* Usage (Windows): > java -classpath . client * * @param args Array of parameters passed to the application * via the command line. */ public static final int PORT = 1789; public static final String greeting = "Hello, Server. This is Client."; public static void main( String[] args ) throws IOException, InterruptedException { System.out.println( "Client attempting connection - \n" ); java.net.Socket client = null; try { // Connect this client to server on known port client = new Socket( "localhost", PORT ); } catch( Exception e ) { System.out.println( "Client connection FAILED.\n" ); System.out.println( "Press " ); byte[] response = new byte[256]; System.in.read( response ); return; } System.out.println( "Client connection SUCCEEDED.\n" ); java.io.InputStream in = client.getInputStream(); java.io.OutputStream out = client.getOutputStream(); System.out.println( "Client sending: " + greeting + "\n" ); out.write( greeting.getBytes() ); out.flush(); byte[] inputStringBytes = new byte[ 256 ]; int inputLen = in.read( inputStringBytes ); System.out.println( "Client received: " + new String( inputStringBytes, 0, inputLen ) + "\n" ); in.close(); out.close(); client.close(); System.out.println( "\nClient done." ); System.out.println( "Press " ); byte[] response = new byte[256]; System.in.read( response ); } }