Java Reference
In-Depth Information
// skip possible additional crlf from bad http implementations
if (reader.ready()) reader.readLine();
}
Finally, an HTTP OK status report is sent back to the client, together with the number that will be
assigned to the next incoming messages, and the list of messages that was requested by the client:
writer.write ("HTTP/1.0 200 OK\r\n");
writer.write ("Content-Type: text/plain\r\n");
writer.write ("Connection: close\r\n");
// Header is separated from content by a blank line.
writer.write ("\r\n");
writer.write (""+current+"\r\n");
if (start < current - lines.length) start = current -
lines.length;
if (start < 0) start = 0;
for (int i = start; i < current; i++) {
writer.write (lines [i % lines.length]);
writer.write ("\r\n");
}
writer.close();
}
The main method of the chat server sets up the server listening to the port given as the command-line
parameter. If no port number was given, it defaults to port 8080 :
public static void main (String [] argv) throws IOException {
if (argv.length == 0)
new ChatServer (8080).run();
else if (argv.length == 1)
new ChatServer (Integer.parseInt (argv[0])).run();
else
System.out.println ("Usage: java ChatServer [port]");
}
}
Note
The Java Servlet API provides better support for implementing HTTP-based server applications than
using raw sockets. However, we did not want to introduce an additional dependency for this example
application.
MIDP and PDAP Chat Clients
Now, you have developed a simple HTTP based chat server. You can test it using a simple Web
browser. By starting the server on the local machine and pointing a Web browser to the address
http://localhost:8080 , you can get a list of the 10 most recent messages. This list will
probably be empty, but you can use a very simple HTML page to send messages to the server:
Search WWH ::




Custom Search