1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| package exercise01; import java.io.*; import java.net.*; public class Client { private String hostname; private int port; Socket socket = null; public Client(String hostname, int port){ this.hostname = hostname; this.port = port; } public void connect() throws UnknownHostException, IOException{ System.out.println("Attempting connect to "+ hostname +":"+port); socket = new Socket(hostname,port); System.out.println("Connection established!"); } public void readResponse() throws IOException{ String userInput; BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println("Response from the server:"); while((userInput = reader.readLine() )!= null ){ System.out.println(userInput); } } public static void main(String[] argv){ Client client = new Client("localhost",8181); try{ client.connect(); client.readResponse(); }catch(UnknownHostException ukhe){ System.err.println("Host unknown! Connection can not be established!"); }catch(IOException ioe){ System.err.println("Connection can not be established! The server may not be on! Check the error message! "+ioe.getMessage()); } } }
|