Java Network programming Question:

Download Job Interview Questions and Answers PDF

What is JHTTP Web Server?

Java Network programming Interview Question
Java Network programming Interview Question

Answer:

Example shows the main JHTTP class. As in the previous two examples, the main( ) method of JHTTP handles initialization, but other programs could use this class themselves to run basic web servers.

Example: The JHTTP Web Server

import java.net.*;
import java.io.*;
import java.util.*;

public class JHTTP extends Thread {

private File documentRootDirectory;
private String indexFileName = "index.html";
private ServerSocket server;
private int numThreads = 50;

public JHTTP(File documentRootDirectory
, int port,
String indexFileName) throws IOException
{

if (!documentRootDirectory.isDirectory( ))
{
throw new IOException(documentRootDirectory
+ " does not exist as a directory");
}
this.documentRootDirectory =
documentRootDirectory;
this.indexFileName = indexFileName;
this.server = new ServerSocket(port);
}

public JHTTP(File documentRootDirectory, int port)
throws IOException {
this(documentRootDirectory, port, "index.html");
}

public JHTTP(File documentRootDirectory)
throws IOException {
this(documentRootDirectory, 80, "index.html");
}

public void run( ) {

for (int i = 0; i < numThreads; i++) {
Thread t = new Thread(
new RequestProcessor(documentRootDirectory,
indexFileName));

t.start( );
}
System.out.println
("Accepting connections on port "
+ server.getLocalPort( ));

System.out.println("Document Root:
" + documentRootDirectory);
while (true) {
try {
Socket request = server.accept( );
RequestProcessor.processRequest(request);
}
catch (IOException e) {
}
}

}

public static void main(String[] args) {

// get the Document root
File docroot;
try {
docroot = new File(args[0]);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println
("Usage: java JHTTP docroot port indexfile");
return;
}

// set the port to listen on
int port;
try {
port = Integer.parseInt(args[1]);
if (port < 0 || port > 65535) port = 80;
}
catch (Exception e) {
port = 80;
}

try {
JHTTP webserver = new JHTTP(docroot, port);
webserver.start( );
}
catch (IOException e) {
System.out.println
("Server could not start because of an "
+ e.getClass( ));
System.out.println(e);
}

}

}


The main( ) method of the JHTTP class sets the document root directory from args[0]. The port is read from args[1], or 80 is used for a default. Then a new JHTTP thread is constructed and started. The JHTTP thread spawns 50 RequestProcessor threads to handle requests, each of which will retrieve incoming connection requests from the RequestProcessor pool as they become available. The JHTTP thread repeatedly accepts incoming connections and puts them in the RequestProcessor pool. .

Download Java Network programming Interview Questions And Answers PDF

Previous QuestionNext Question
What is an HTTP Redirector?What is a Thread Pool?