CS 051 Fall 2012

Lecture 36

Sockets

Our previous URL example returned the contents of a web page. The URL object hid
a lot of the details from us. To understand these details, we look at an example that does the same thing
using a Socket.

If we want to communicate with a machine over a network, we need to be able to send as well as
receive data. Sockets allow us to do this.

A Socket is like a phone connection. You can think of a phone connection as a bundle of two
separate connections. The first takes data from the mouthpiece of your phone, and sends it to
the earpiece of the other phone. The second connection takes data from the mouthpiece of the
othere phone, and sends it to your earpiece.

A Socket is similarly composed of two streams. The client writes on one stream, which the server
reads from. And the server writes on the other stream, which the client reads from. In our telnet
example, the server writes to a stream with the results of the commands that we sent it on the
other stream.

HTMLLinkFinder with Sockets

The class example HTMLLinkFinderUsingSockets fetches the text of
a web page just like our previous example, except that it uses Sockets in
its implementation.

To use a Java Socket, we need to create a connection, then get the two Streams that we describe
above. Here is sample code that does these basic steps:

    Socket tcpSocket = new Socket("www.cs.pomona.edu", 80);

    BufferedReader input = 
            new BufferedReader(new InputStreamReader(tcpSocket.getInputStream()));
            
    PrintWriter output = 
            new PrintWriter(tcpSocket.getOutputStream(), true);

Note that a PrintWriter is similar to a FileWriter, except that FileWriter
can only write Strings or arrays of characters. PrintWriter can output all
types, just like System.out.println().

The boolean value true that we send to the PrintWriter constructor tells the
PrintWriter that is should flush the output stream after calls to println, printf,
or format.

Now that the connection is established, we can request a web page by writing the GET command on
the output stream. For example:

    output.println("GET " + pageName);

To get my home page, we would set pageName to "/~kcoogan/index.html"

The server's response to our command will be written on the server's output stream, which is the
client's input stream. We can get it in the client the same way we read any input stream:

    String response = "";
    
    String curline = input.readLine();
    while(curline != null) {
        response = response + "\n" + curline;
        curline = input.readLine();
    }

    return response;

Drawing Panel Network

The class example DrawingPanelNetwork allowed us to open two instances of
the program, and send objects back and forth between them. This technique used Sockets,
and works equally well when the program instances are not on the same machine. You will be
writing a very similar program for your next lab.