import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; /* * This class demonstrates how to connect to a server on a port * through a socket, establish text-based input and output streams, * and communicate by sending and receiving text-based data. */ public class NetTest { // the host to connect to static String host = "sciris.shu.edu"; // the port on which to connect static int port = 80; // standard program entry point public static void main(String[] args) { // The connection attempt must be embedded in a 'try-catch' block // to catch the many errors that could occur during communications try { // Connecting using the java.net.Socket class System.out.println("Connecting ..."); Socket socket = new Socket(host, port); System.out.println("Connected: " + socket); // Setting up an output stream with text translation and buffering. // This output stream can then be used to send data to the host. OutputStream outstream = socket.getOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(outstream); PrintWriter out = new PrintWriter(writer); // Setting up an input stream with text translation and buffering. // This input stream can be used to receive data from the host. InputStream instream = socket.getInputStream(); InputStreamReader reader = new InputStreamReader(instream); BufferedReader in = new BufferedReader(reader); // Now connection is established, IO is setup, we can now 'talk' // Sending an http 1.1 GET request to the host out.println("GET / HTTP/1.1"); out.println("Host: " + host); out.println(); // Data accumulates in stream buffer; must be 'flushed' to send out.flush(); // GET request is sent, expecting an answer. We read the answer from // the input stream line by line in a while loop, since we don't know // how many lines will come in. Each line is printed to standard out. String line = in.readLine(); while (line != null) { System.out.println(line); line = in.readLine(); } // Done, so closing streams and socket out.close(); in.close(); socket.close(); } catch (UnknownHostException e) { // Printing error message for unknown host exception e.printStackTrace(); } catch (IOException e) { // Printing error message for all other IO exceptions e.printStackTrace(); } } }