Talking to a Web server |
Now, let's consider how to make an HTTP connection in Java. (Because of Java's URL class, we don't actually need to do this, but it helps understand how the network connection is created and used.)
We need to first create a connection. To do this we create a Socket passing in the name of the machine and the port number. For example, to connect to our Web server we would say:
Socket tcpSocket = new Socket("portal.dci.pomona.edu", 80);
A socket is a lot like a phone connection. When a phone connection is established, you can actually think of this as two connections bundled together. One of these connections alllows you to speak and to your mouthpiece and be heard via the earpiece on the other end. The other connection allows the other person to speak into a mouthpiece and for you to hear what they are saying in your earpiece.
A socket is similarly composed of two streams. The client writes on one stream which the server reads from. This stream is used to send commands from the client to the server. The server writes on another stream which the client reads from. The server uses this stream to send the results of commands to the client.
The next step in writing a client in Java is to get the stream to write to and the stream to read from and create a writer and a reader for them. Notice that we need to make slightly different calls to create the reader and writer, but once created we can use them in the same way as earlier streams:
// Get the stream reader and writer to enable communication input = new BufferedReader( new InputStreamReader(tcpSocket.getInputStream())); 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 as System.out.println.
Now that the connection is established, we can request a Web page by writing the GET command on the output stream. So, to get a Web page, we send the GET command to the server:
output.println("GET " + pageName);
To get to my home page, we would set pageName to "/~kim/".
Now, we need to read the Web page that the server returns over the network connection. This a loop with a style familiar to what we have seen before:
String response = ""; String curline = input.readLine(); while (curline != null) { response = response + "\ n" + curline; curline = input.readLine(); } return response;
HTMLLinkFinderUsingSockets is the complete code to manage an HTTP connection.
Talking to a Web server |