Interview Questions

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

Java Network Programming - Sockets for Servers


(Continued from previous question...)

If you don't 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.\r\n");        
          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);
    }

Example 11-2 implements a simple daytime server, as per RFC 867. Since this server just sends a single line of text in response to each connection, it processes each connection immediately. More complex servers should spawn a thread to handle each request. In this case, the overhead of spawning a thread would be greater than the time needed to process the request.

NOTE: If you run this program on a Unix box, you need to run it as root in order to connect to port 13. If you don't want to or can't run it as root, change the port number to something above 1024, say 1313.

(Continued on next question...)

Other Interview Questions