Interview Questions

Example : A Random Port

Java Network Programming - Sockets for Servers


(Continued from previous question...)

Example : A Random Port

    Example: A Random Port

    import java.net.*;
    import java.io.*;
     
    public class RandomPort {
     
 public static void main(String[] args) {
     
        try {
ServerSocket server = new ServerSocket(0);
System.out.println("This server runs on port " 
           + server.getLocalPort(  ));
        }
        catch (IOException e) {
          System.err.println(e);
        }
     
      }
     
    }

Here's the output of several runs:

D:\JAVA\JNP2\examples\11>java RandomPort
This server runs on port 1154
D:\JAVA\JNP2\examples\11>java RandomPort
This server runs on port 1155
D:\JAVA\JNP2\examples\11>java RandomPort
This server runs on port 1156

At least on this VM, the ports aren't really random; but they are at least indeterminate until runtime. Socket Options

The only socket option supported for server sockets is SO_TIMEOUT. SO_TIMEOUT is the amount of time, in milliseconds, that accept( ) waits for an incoming connection before throwing a java.io.InterruptedIOException. If SO_TIMEOUT is 0, then accept( ) will never time out. The default is to never time out.

Using SO_TIMEOUT is rather rare. You might need it if you were implementing a complicated and secure protocol that required multiple connections between the client and the server where some responses needed to occur within a fixed amount of time. Most servers are designed to run for indefinite periods of time and therefore use the default timeout value, which is 0 (never time out). public void setSoTimeout(int timeout) throws SocketException

The setSoTimeout( ) method sets the SO_TIMEOUT field for this server socket object. The countdown starts when accept( ) is invoked. When the timeout expires, accept( ) throws an InterruptedIOException. You should set this option before calling accept( ); you cannot change the timeout value while accept( ) is waiting for a connection. The timeout argument must be greater than or equal to zero; if it isn't, the method throws an IllegalArgumentException. For example:

    try {
ServerSocket server = new ServerSocket(2048);
server.setSoTimeout(30000); 
// block for no more than 30 seconds
      try {
        Socket s = server.accept(  );
        // handle the connection
        // ...
      }
      catch (InterruptedIOException e) {
System.err.println
     ("No connection within 30 seconds");
      }
      finally {
        server.close(  );
      }
    catch (IOException e) {
 System.err.println
      ("Unexpected IOException: " + e);
    }

public int getSoTimeout( ) throws IOException

The getSoTimeout( ) method returns this server
socket's current SO_TIMEOUT value. For example:

public void printSoTimeout(ServerSocket server)
{
     
      int timeout = server.getSoTimeOut(  );
      if (timeout > 0) {
System.out.println(server + " will time out after " 
         + timeout + "milliseconds.");
      }
System.out.println(server + " will never time out.");
      }
      else {
System.out.println("Impossible condition occurred in " 
     + server);
System.out.println("Timeout cannot be less than zero." );
      }
     
    }

The Object Methods
jServerSocket overrides only one of the standard methods from java.lang.Object, toString( ). Thus, equality comparisons test for strict identity, and server sockets are problematic in hash tables. Normally, this isn't a large problem.

public String toString( )

A String returned by ServerSocket's toString( ) method looks like this:

ServerSocket[addr=0.0.0.0,port=0,localport=5776]

In current implementations, addr is always 0.0.0.0 and port is always 0. Presumably, these may become something more interesting in the future. The localport is the local port on which the server is listening for connections.

Implementation
The ServerSocket class provides two methods for changing the default implementation of server sockets. I'll describe them only briefly here, since they're primarily intended for implementers of Java virtual machines rather than application programmers.

public static synchronized void setSocketFactory (SocketImpl Factory fac) throws IOException

This method sets the system's server SocketImplFactory, which is the factory used to create ServerSocket objects. This is not the same factory that is used to create client Socket objects, though the syntax is similar; you can have one factory for Socket objects and a different factory for ServerSocket objects. You can set this factory only once in a program, however. A second attempt to set the SocketImplFactory throws a SocketException.

Protected final void implAccept(Socket s) throws IOException

Subclasses of ServerSocket use this method to implement accept( ). You pass an unconnected Socket object to implAccept( ). (Doing this requires you to subclass Socket as well since the standard java.net.Socket class doesn't provide a means to create unconnected sockets.) When the method returns, the Socket argument s is connected to a client.

Some Useful Servers

This section shows several servers you can build with server sockets. It starts with a server you can use to test client responses and requests, much as you use Telnet to test server behavior. Then we present three different HTTP servers, each with a different special purpose and each slightly more complex than the previous one.

(Continued on next question...)

Other Interview Questions