Java Reference
In-Depth Information
When a connection is made, a Socket object is returned. This object is passed onto
the handleClientSession method to fulfill the request.
handleClientSession(clientSocket);
A catch block is also provided to handle any exceptions. If an exception occurs, it will
be displayed to the console, and the server will continue to run.
} catch (IOException e)
{
e.printStackTrace();
}
Once a connection is established, the handleClientSession method is called.
This method begins by obtaining an InputStream to the socket. The InputStream
is passed into an InputStreamReader , and then to a BufferedReader . This
allows the readLine function to read the socket as a series of lines.
// Setup to read from the socket in lines.
InputStream is = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(is);
BufferedReader in = new BufferedReader(inputStreamReader);
Next, an OutputStream for the socket is created. The OutputStream
will allow a socket to be written to. The OutputStream object is used to construct a
PrintStream object. Using a PrintStream object will allow the println meth-
od to write lines of text to the OutputStream .
// Setup to write to socket in lines.
OutputStream os = socket.getOutputStream();
PrintStream out = new PrintStream(os);
Now that the streams are setup, it is time to begin reading from the socket. As was dis-
cussed earlier in the chapter, the first line of an HTTP request has a special format. Because
of this, the first line is read separately. It is then printed out.
// Read in the first line.
System.out.println("**New Request**");
String first = in.readLine();
System.out.println(first);
Once the first line has been read in, the headers can be read. The headers are read until
a blank line is found. As was discussed earlier in this chapter, a blank line indicates the end
of HTTP headers.
// Read in headers and post data.
String line;
do
{
Search WWH ::




Custom Search