In a world which is wired, standalone applications are becoming obsolete. The facilitators for the connectivity of applications, at a low level, are sockets. Any language, whether high-level or low-level, must provide APIs to handle sockets if its creators want it to be widely accepted.
Socket Programming in Java - Socket programming in the real world (Page 3 of 4 )
It's time to put theory to practice. The file server to be developed will provide the following services:
List the files that can be downloaded.
Send the selected file.
Process each request in a separate thread.
This example is from the solution to an exercise from Professor David Eck’s on-line textbook, published under an open content license at http://math.hws.edu/eck/cs124/javanotes4/c10/ex-10-4-
answer.html.
There are two classes that form the server:
FileServer - sets up the server.
ConnectionHandler - services the requests for sending files to clients.
Let's look at the implementation. First comes the FileServer class. It does the following tasks:
Checks the existence of the directory name specified.
Sets up the server.
Delegates the requests to be handled to an object of the ConnectionHandler class.
the following is the implementation of the class:
import java.net.*; import java.io.*;
public class FileServer {
static final int LISTENING_PORT = 3210;
public static void main(String[] args) {
File directory; // The directory from which the // gets the files that it serves. ServerSocket listener; // Listens for connection // requests. Socket connection; // A socket for communicating // with a client.
/* Check that there is a command-line argument. If not, print a usage message and end. */
/* Get the directory name from the command line, and make it into a file object. Check that the file exists and is in fact a directory. */
directory = new File(args[0]); if ( ! directory.exists() ) { System.out.println("Specified directory does not exist."); return; } if (! directory.isDirectory() ) { System.out.println("The specified file is not a directory."); return; }
/* Listen for connection requests from clients. For each connection, create a separate Thread of type ConnectionHandler to process it. The ConnectionHandler class is defined below. The server runs until the program is terminated, for example by a CONTROL-C. */
try { listener = new ServerSocket(LISTENING_PORT); System.out.println("Listening on port " + LISTENING_PORT); while (true) { connection = listener.accept(); new ConnectionHandler(directory,connection); } } catch (Exception e) { System.out.println("Server shut down unexpectedly."); System.out.println("Error: " + e); return; }