Java Reference
In-Depth Information
socket.close();
}
catch (Exception e) {
e.printStackTrace (System.err);
}
}
}
The main functionality of the chat server is performed in the handleRequest() method. It gets the
socket reader and writer as input from the run() method. At first, it reads the HTTP request line from
the client and prints it to system.out:
public void handleRequest (BufferedReader reader,
Writer writer) throws IOException {
String request = reader.readLine();
System.out.println ("handling: "+request);
The next step is to analyze the request line. For that purpose, it is divided into the method, the
requested address, and the version part, which are separated by space characters:
int s0 = request.indexOf (' ');
int s1 = request.indexOf (' ', s0+1);
String method = request.substring (0, s0);
String url = request.substring (s0+1, s1);
Now, the first line to be submitted is determined by analyzing the request URL:
int start = -1; // default;
int cut = url.indexOf ("?start=");
if (cut != -1)
start = Integer.parseInt (url.substring (cut+7));
if (start < 0) start = count - 10;
Additional header lines are skipped by reading from the stream until an empty line or the end of the
stream is reached. An empty line marks the end of the HTTP headers and the beginning of the content
of the request:
while (true) {
String s = reader.readLine();
System.out.println ("header: "+s);
if (s == null || s.length() == 0) break;
}
Now, if the HTTP-Request method is POST , the nickname and the sender are read from the HTTP
content. A corresponding string is appended to the message ring buffer of the server:
if (method.equalsIgnoreCase ("post")) {
String nick = reader.readLine().substring (5);
String text = reader.readLine().substring (5);
System.out.println ("nick="+nick);
System.out.println ("text="+text);
lines [(current++) % lines.length] = nick + ": "+ text;
Search WWH ::




Custom Search