Java Network programming Interview Preparation Guide
Download PDF
Add New Question

Java Network programming Interview Questions and Answers will guide us now that Networking classes included in standard Java are considered one of better and complete solutions amongst modern languages, with simple syntax and semantics, although they are being used for objective which is not too easy to implement: distributed programming. So learn more about Java Network Programing or get job preparation in Java Network programming with this Java Network programming Interview Questions Answers

12 Java Network programming Questions and Answers:

1 :: If you do not want your program to halt while it waits for a connection, put the call to accept( ) in a separate thread?

If you don't want your program to halt while it waits for a connection, put the call to accept( ) in a separate thread.

When you add exception handling, the code becomes somewhat more convoluted. It's important to distinguish between exceptions thrown by the ServerSocket, which should probably shut down the server and log an error message, and exceptions thrown by a Socket, which should just close that active connection. Exceptions thrown by the accept( ) method are an intermediate case that can go either way. To do this, you'll need to nest your try blocks. Finally, most servers will want to make sure that all sockets they accept are closed when they're finished. Even if the protocol specifies that clients are responsible for closing connections, clients do not always strictly adhere to the protocol. The call to close( ) also has to be wrapped in a try block that catches an IOException. However, if you do catch an IOException when closing the socket, ignore it. It just means that the client closed the socket before the server could. Here's a slightly more realistic example:

try {
ServerSocket server = new ServerSocket(5776);
while (true) {
Socket connection = server.accept( );
try {
OutputStreamWriter out
= new OutputStreamWriter
(connection.getOutputStream( ));
out.write("You've connected to this server.
Bye-bye now.rn");
connection.close( );
}
catch (IOException e) {
// This tends to be a transitory error for
this one connection; e.g. the client
broke the connection early. Consequently,
// we don't want to break the loop or print
an error message. However, you might choose
to log this exception in an error log.//
}
// Most servers will want to guarantee
that sockets are closed
// when complete.
try {
if (connection != null) connection.close( );
}
catch (IOException e) {}
}
}
catch (IOException e) {
System.err.println(e);
}
Post Your Answer

2 :: Public ServerSocket(int port, int queueLength) throws IOException, BindException?

This constructor creates a ServerSocket on the specified port with a queue length of your choosing. If the machine has multiple network interfaces or IP addresses, then it listens on this port on all those interfaces and IP addresses. The queueLength argument sets the length of the queue for incoming connection requests--that is, how many incoming connections can be stored at one time before the host starts refusing connections. Some operating systems have a maximum queue length, typically five. If you try to expand the queue past that maximum number, the maximum queue length is used instead. If you pass 0 for the port number, the system selects an available port.

For example, to create a server socket on port 5,776 that would hold up to 100 incoming connection requests in the queue, you would write:

try {
ServerSocket httpd = new ServerSocket(5776, 100);
}
catch (IOException e) {
System.err.println(e);
}

The constructor throws an IOException (specifically, a BindException) if the socket cannot be created and bound to the requested port. An IOException when creating a ServerSocket almost always means one of two things. Either the specified port is already in use, or you do not have root privileges on Unix and you're trying to connect to a port from 1 to 1,023.
Post Your Answer

3 :: Explain Look for Local Ports?

Example 11-1: Look for Local Ports

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

public class LocalPortScanner {

public static void main(String[] args) {

for (int port = 1; port <= 65535; port++)
{

try {

// the next line will fail and drop into the
catch block if there is already a server
running on the port//

ServerSocket server = new ServerSocket(port);
}
catch (IOException e) {
System.out.println("There is a server on port
" + port + ".");
} // end try

} // end for

}

}

Here's the output I got when running
LocalPortScanner on my NT workstation:

D:JAVAJNP2examples11>java LocalPortScanner
There is a server on port 135.
There is a server on port 1025.
There is a server on port 1026.
There is a server on port 1027.
There is a server on port 1028.
Post Your Answer

4 :: To create a Socket, you need to know the Internet host to which you want to connect?

To create a Socket, you need to know the Internet host to which you want to connect. When you're writing a server, you don't know in advance who will contact you, and even if you did, you wouldn't know when that host wanted to contact you. In other words, servers are like receptionists who sit by the phone and wait for incoming calls. They don't know who will call or when, only that when the phone rings, they have to pick it up and talk to whoever is there. We can't program that behavior with the Socket class alone. Granted, there's no reason that clients written in Java have to talk to Java servers--in fact, a client doesn't care what language the server was written in or what platform it runs on. However, if Java didn't let us write servers, there would be a glaring hole in its capabilities.

Fortunately, there's no such hole. Java provides a ServerSocket class to allow programmers to write servers. Basically, a server socket's job is to sit by the phone and wait for incoming calls. More technically, a ServerSocket runs on the server and listens for incoming TCP connections. Each ServerSocket listens on a particular port on the server machine. When a client Socket on a remote host attempts to connect to that port, the server wakes up, negotiates the connection between the client and the server, and opens a regular Socket between the two hosts. In other words, server sockets wait for connections while client sockets initiate connections. Once the server socket has set up the connection, the server uses a regular Socket object to send data to the client. Data always travels over the regular socket.

The ServerSocket Class

The ServerSocket class contains everything you need to write servers in Java. It has constructors that create new ServerSocket objects, methods that listen for connections on a specified port, and methods that return a Socket object when a connection is made so that you can send and receive data. In addition, it has methods to set various options and the usual miscellaneous methods such as toString( ).

The basic life cycle of a server is:

1. A new ServerSocket is created on a particular port using a ServerSocket( ) constructor.
2. The ServerSocket listens for incoming connection attempts on that port using its accept( ) method. accept( ) blocks until a client attempts to make a connection, at which point accept( ) returns a Socket object connecting the client and the server.
3. Depending on the type of server, either the Socket's getInputStream( ) method, getOutputStream( ) method, or both are called to get input and output streams that communicate with the client.
4. The server and the client interact according to an agreed-upon protocol until it is time to close the connection.
5. The server, the client, or both close the connection.
6. The server returns to step 2 and waits for the next connection.
Post Your Answer

5 :: Explain A Daytime Server?

Example: A Daytime Server

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

public class DaytimeServer {

public final static int DEFAULT_PORT = 13;

public static void main(String[] args) {

int port = DEFAULT_PORT;
if (args.length > 0) {
try {
port = Integer.parseInt(args[0]);
if (port < 0 || port >= 65536) {
System.out.println("Port must between 0 and
65535");
return;
}
}
catch (NumberFormatException e) {
// use default port
}

}

try {

ServerSocket server = new ServerSocket(port);

Socket connection = null;
while (true) {

try {
connection = server.accept( );
OutputStreamWriter out
= new OutputStreamWriter
(connection.getOutputStream( ));
Date now = new Date( );
out.write(now.toString( ) +"rn");
out.flush( );
connection.close( );
}
catch (IOException e) {}
finally {
try {
if (connection != null) connection.close( );
}
catch (IOException e) {}
}

} // end while

} // end try
catch (IOException e) {
System.err.println(e);
} // end catch

} // end main

} // end DaytimeServer

Example is straightforward. The first three lines import the usual packages, java.io and java.net, as well as java.util.Date so we can get the time. There is a single public final static int field (i.e., a constant) in the class DEFAULT_PORT, which is set to the well-known port for a daytime server (port 13). The class has a single method, main( ), which does all the work. If the port is specified on the command-line, then it's read from args[0]. Otherwise, the default port is used.

The outer try block traps any IOExceptions that may arise while the ServerSocket server is constructed on the daytime port or when it accepts connections. The inner try block watches for exceptions thrown while the connections are accepted and processed. The accept( ) method is called within an infinite loop to watch for new connections; like many servers, this program never terminates but continues listening until an exception is thrown or you stop it manually.[1]

When a client makes a connection, accept( ) returns a Socket, which is stored in the local variable connection, and the program continues. We call getOutputStream( ) to get the output stream associated with that Socket and then chain that output stream to a new OutputStreamWriter, out. To get the current date, we construct a new Date object and send it to the client by writing its string representation on out with write( ).

Finally, after the data is sent or an exception has been thrown, we close connection inside the finally block. Always close a socket when you're finished with it. In the previous chapter, we said that a client shouldn't rely on the other side of a connection to close the socket. That goes triple for servers. Clients can time out or crash; users can cancel transactions; networks can go down in high-traffic periods. For any of these or a dozen more reasons, you cannot rely on clients to close sockets, even when the protocol requires them to (which it doesn't in this case).
Post Your Answer
Add New Question