Java Network programming Interview Questions and Answers

Java Network programming Questions and Answers:

1 :: What is a Thread Pool?

Each connection is handled by the run( ) method of the RequestProcessor class shown in Example. This method waits until it can get a Socket out of the pool. Once it does that, it gets input and output streams from the socket and chains them to a reader and a writer. The reader reads the first line of the client request to determine the version of HTTP that the client supports--we want to send a MIME header only if this is HTTP 1.0 or later--and what file is requested. Assuming the method is GET, the file that is requested is converted to a filename on the local filesystem. If the file requested was a directory (i.e., its name ended with a slash), we add the name of an index file. We use the canonical path to make sure that the requested file doesn't come from outside the document root directory. Otherwise, a sneaky client could walk all over the local filesystem by including .. in URLs to walk up the directory hierarchy. This is all we'll need from the client, though a more advanced web server, especially one that logged hits, would read the rest of the MIME header the client sends.

Next the requested file is opened and its contents are read into a byte array. If the HTTP version is 1.0 or later, we write the appropriate MIME headers on the output stream. To figure out the content type, we call the guessContentTypeFromName( ) method to map file extensions such as .html onto MIME types such as text/html. The byte array containing the file's contents is written onto the output stream, and the connection is closed. Exceptions may be thrown at various places if, for example, the file cannot be found or opened. If an exception occurs, we send an appropriate HTTP error message to the client instead of the file's contents
0/5 Rating (0 vote)
Is This Answer Correct?    0 Yes 0 No
Place Your Answer

2 :: What is JHTTP Web Server?

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. .
0/5 Rating (0 vote)
Is This Answer Correct?    0 Yes 0 No
Place Your Answer

3 :: What is an HTTP Redirector?

Another simple but useful application for a special-purpose HTTP server is redirection. In this section, we develop a server that redirects users from one web site to another--for example, from cnet.com to home.cnet.com. Example reads a URL and a port number from the command-line, opens a server socket on the port, then redirects all requests that it receives to the site indicated by the new URL, using a 302 FOUND code. Chances are this server is fast enough not to require multiple threads. Nonetheless, threads might be mildly advantageous, especially on a high-volume site on a slow network connection. And this server does a lot of string processing, one of Java's most notorious performance bottlenecks.
0/5 Rating (0 vote)
Is This Answer Correct?    0 Yes 0 No
Place Your Answer

4 :: What is an HTTP Server?

HTTP is a large protocol. A full-featured HTTP server must respond to requests for files, convert URLs into filenames on the local system, respond to POST and GET requests, handle requests for files that don't exist, interpret MIME types, launch CGI programs, and much, much more. However, many HTTP servers don't need all of these features. For example, many sites simply display an "under construction" message. Clearly, Apache is overkill for a site like this. Such a site is a candidate for a custom server that does only one thing. Java's network class library makes writing simple servers like this almost trivial.

Custom servers aren't useful only for small sites. High-traffic sites like Yahoo! are also candidates for custom servers because a server that does only one thing can often be much faster than a general purpose server such as Apache or Netscape. It is easy to optimize a special purpose server for a particular task; the result is often much more efficient than a general purpose server that needs to respond to many different kinds of requests. For instance, icons and images that are used repeatedly across many pages or on high-traffic pages might be better handled by a server that read all the image files into memory on startup, and then served them straight out of RAM rather than having to read them off disk for each request. Furthermore, this server could avoid wasting time on logging if you didn't want to track the image request separately from the requests for the pages they were included in.

Finally, Java isn't a bad language for feature-full web servers meant to compete with the likes of Apache or AOLServer. Although CPU-intensive Java programs are demonstrably slower than CPU-intensive C and C++ programs, even when run under a JIT, most HTTP servers are limited by bandwidth, not by CPU speed. Consequently, Java's other advantages, such as its half-compiled/half-interpreted nature, dynamic class loading, garbage collection, and memory protection, really get a chance to shine. In particular, sites that make heavy use of dynamic content through CGI scripts, PHP pages, or other mechanisms can often run much faster when reimplemented on top of a pure or mostly pure Java web server. Indeed, there are several production web servers written in Java such as the W3C's testbed server Jigsaw (http://www.w3.org/Jigsaw/). Many other web servers written in C now include substantial Java components to support the Java Servlet API and Java Server Pages. On many sites, these are replacing the traditional CGIs, ASPs, and server-side includes, mostly because the Java equivalents are faster and less resource-intensive.

Investigation of HTTP servers begins with a server that always sends out the same file, no matter who or what the request. This is shown in Example, SingleFileHTTPServer. The filename, local port, and content encoding are read from the command line. If the port is omitted, port 80 is assumed. If the encoding is omitted, ASCII is assumed.
0/5 Rating (0 vote)
Is This Answer Correct?    0 Yes 0 No
Place Your Answer

5 :: What is a Client Tester?

Example is a program called ClientTester that runs on a port specified on thecommand-line, shows all data sent by the client, and allows you to send a response to the client by typing it on the command line. For example, you can use this program to see the commands that Netscape Navigator sends to a server.

NOTE: Clients are rarely as forgiving about unexpected server responses as servers are about unexpected client responses. If at all possible, try to run the clients that connect to this program on a Unix system or some other platform that is moderately crash-proof. Don't run them on a Mac or Windows 98, which are less stable.

This program uses two threads: one to handle input from the client and the other to send output from the server. Using two threads allows the program to handle input and output simultaneously: it can be sending a response to the client while receiving a request--or, more to the point, it can send data to the client while waiting for the client to respond. This is convenient because different clients and servers talk in unpredictable ways. With some protocols, the server talks first; with others, the client talks first. Sometimes the server sends a one-line response; often, the response is much larger. Sometimes the client and the server talk at each other simultaneously. Other times, one side of the connection waits for the other to finish before it responds. The program must be flexible enough to handle all these cases. Example shows the code.

Example : A Client Tester

import java.net.*;
import java.io.*;
import com.macfaq.io.SafeBufferedReader;
//


public class ClientTester {

public static void main(String[] args) {

int port;

try {
port = Integer.parseInt(args[0]);
}
catch (Exception e) {
port = 0;
}

try {
ServerSocket server = new ServerSocket
(port, 1);
System.out.println
("Listening for connections on port "
+ server.getLocalPort( ));

while (true) {
Socket connection = server.accept( );
try {
System.out.println
("Connection established with "+ connection);
Thread input = new InputThread
(connection.getInputStream( ));
input.start( );
Thread output
= new OutputThread
(connection.getOutputStream( ));
output.start( );
// wait for output and input to finish
try {
input.join( );
output.join( );
}
catch (InterruptedException e) {
}
}
catch (IOException e) {
System.err.println(e);
}
finally {
try {
if (connection !=
null) connection.close( );
}
catch (IOException e) {}
}
}
}
catch (IOException e) {
e.printStackTrace( );
}

}

}

class InputThread extends Thread {

InputStream in;

public InputThread(InputStream in) {
this.in = in;
}

public void run( ) {

try {
while (true) {
int i = in.read( );
if (i == -1) break;
System.out.write(i);
}
}
catch (SocketException e) {
// output thread closed the socket
}
catch (IOException e) {
System.err.println(e);
}
try {
in.close( );
}
catch (IOException e) {
}

}

}

lass OutputThread extends Thread {

Writer out;

public OutputThread(OutputStream out) {
this.out = new OutputStreamWriter(out);
}

public void run( ) {

String line;
BufferedReader in
= new SafeBufferedReader
(new InputStreamReader(System.in));
try {
while (true) {
line = in.readLine( );
if (line.equals(".")) break;
out.write(line +"rn");
out.flush( );
}
}
catch (IOException e) {
}
try {
out.close( );
}
catch (IOException e) {
}

}

}
0/5 Rating (0 vote)
Is This Answer Correct?    0 Yes 0 No
Place Your Answer

Rate This Category:
0/5 Rating (0 vote)
Place Your Question



Top: Java Network programming Interview Questions and Answers
Java Network programming Interview Questions and Answers

Top Frequently Asked Java Network programming Question
Frequently Asked Java Network programming Job Interview Question


Top Frequently opened Networking Job Interview categories
Most popular Networking Job Interview categories

Comments About Java Network programming Interview Questions and Answers

Share your valuable opinions, ideas and suggestions about Java Network programming Interview Questions and Answers
While placing your comment your email address is required but won't be published any where else; Personal information will be kept confidential; we do not sell or release our respective visitors private information.
  1. Webmaster 22nd of May 2012

    Webmaster Said

    Tell us what you feel about Java Network programming Interview Questions and Answers
    All comments will be published after review. No login or registration is required to post a comment on Java Network programming Interview Questions and Answers We offer and invite you to submit your valuable comment now; Please be respectful of others when commenting. Insulting others, self-promotional comments, website promotional comments, marketing stuff, SEO Techniques, SMS-style content and off-topic comments will not be approved at this information portal.
    So start sharing your thoughts regarding Java Network programming Interview Questions and Answers
    Thank you.

Leave a Comment

Leave a Comment
  1.  Enter This Verification Code  Regenerate Verification Code  



Your reply will be added to the comment above (Below any other replies to this comment) -

Top Comments About: Java Network programming Interview Questions and Answers
Comments on Java Network programming Interview Questions and Answers

 
Top of Link batk to Java Network programming Interview Questions and Answers
Link batk to Java Network programming Interview Questions and Answers