CSC419 · 2081 · 10 marks
What is the task of the Listener interface? Write a socket program for a file server that makes a collection of files available for transmission to clients. When a client connects to the server, the server first reads a one-line command from the client. The command string can be of the form 'GET ',
What is the task of the Listener interface? Write a socket program for a file server that makes a collection of files available for transmission to clients. When a client connects to the server, the server first reads a one-line command from the client. The command string can be of the form 'GET ', where is a file name. The server checks whether the requested file actually exists. If so, it first sends the word 'OK' as a message to the client. Then it sends the contents of the file and closes the connection. Otherwise, it sends 'ERROR' to the client as message and closes the connection. Assume that there is no sub directories.[10]
Quick answer
The Listener interface (specifically ServerSocket in Java TCP socket programming) is responsible for listening for incoming client connection requests on a specified port number.
Listener Interface and File Server Socket Program
Part 1: Task of the Listener Interface
Key Tasks of the Listener (ServerSocket):
- It waits and listens on a specific port for any client attempting to make a connection.
- When a client request arrives, it accepts the connection using the
accept()method, which returns aSocketobject representing the client connection. - It acts as the entry point for the server side of a TCP connection.
- It allows the server to communicate with multiple clients by repeatedly calling
accept(). - It manages the binding of the server to a port so clients know where to connect.
In Java, the typical usage is:
ServerSocket ss = new ServerSocket(portNumber);
Socket cs = ss.accept(); // blocks until a client connects
Part 2: File Server Socket Program
Design Logic (Step by Step):
- Server creates a
ServerSocketand listens on a port. - Client connects and sends a command like
GET filename.txt. - Server parses the command and extracts the filename.
- Server checks if the file exists in the current directory.
- If file exists: sends
OK, then sends file contents line by line, then closes. - If file does not exist: sends
ERROR, then closes.
Server Program: FileServer.java
import java.net.*;
import java.io.*;
public class FileServer {
public static void main(String[] args) throws IOException {
// Step 1: Create ServerSocket and listen on port 1254
ServerSocket ss = new ServerSocket(1254);
System.out.println("File Server started. Waiting for clients...");
// Step 2: Keep server running to accept multiple clients
while (true) {
// Step 3: Accept incoming client connection
Socket cs = ss.accept();
System.out.println("Client connected: " + cs.getInetAddress());
// Step 4: Get input and output streams
BufferedReader in = new BufferedReader(
new InputStreamReader(cs.getInputStream())
);
PrintWriter out = new PrintWriter(cs.getOutputStream(), true);
// Step 5: Read the command sent by client (e.g., "GET filename.txt")
String command = in.readLine();
System.out.println("Command received: " + command);
// Step 6: Parse the command
if (command != null && command.startsWith("GET ")) {
// Extract filename from command
String filename = command.substring(4).trim();
// Step 7: Check if file exists (no subdirectories assumed)
File file = new File(filename);
if (file.exists() && file.isFile()) {
// Step 8a: File found - send OK
out.println("OK");
System.out.println("Sending file: " + filename);
// Step 9: Read file and send contents line by line
BufferedReader fileReader = new BufferedReader(
new FileReader(file)
);
String line;
while ((line = fileReader.readLine()) != null) {
out.println(line);
}
fileReader.close();
System.out.println("File sent successfully.");
} else {
// Step 8b: File not found - send ERROR
out.println("ERROR");
System.out.println("File not found: " + filename);
}
} else {
// Invalid command format
out.println("ERROR");
System.out.println("Invalid command received.");
}
// Step 10: Close streams and connection
in.close();
out.close();
cs.close();
System.out.println("Connection closed.");
}
}
}
Client Program: FileClient.java
import java.net.*;
import java.io.*;
public class FileClient {
public static void main(String[] args) throws IOException {
// Step 1: Open a socket to connect to the server
Socket cs = new Socket("localhost", 1254);
// Step 2: Open input and output streams
BufferedReader in = new BufferedReader(
new InputStreamReader(cs.getInputStream())
);
PrintWriter out = new PrintWriter(cs.getOutputStream(), true);
// Step 3: Send GET command to the server
String filename = "hello.txt"; // filename to request
out.println("GET " + filename);
System.out.println("Request sent: GET " + filename);
// Step 4: Read the server's first response (OK or ERROR)
String response = in.readLine();
System.out.println("Server Response: " + response);
if (response != null && response.equals("OK")) {
// Step 5: Read and display the file contents
System.out.println("--- File Contents ---");
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
System.out.println("--- End of File ---");
} else {
// File not found on server
System.out.println("Requested file does not exist on server.");
}
// Step 6: Close streams and socket
in.close();
out.close();
cs.close();
}
}
Sample Output
When hello.txt exists on server:
Server side:
File Server started. Waiting for clients...
Client connected: /127.0.0.1
Command received: GET hello.txt
Sending file: hello.txt
File sent successfully.
Connection closed.
Client side:
Request sent: GET hello.txt
Server Response: OK
--- File Contents ---
Hello, this is a test file.
Welcome to File Server.
--- End of File ---
When missing.txt does NOT exist:
Client side:
Request sent: GET missing.txt
Server Response: ERROR
Requested file does not exist on server.
Server side:
Client connected: /127.0.0.1
Command received: GET missing.txt
File not found: missing.txt
Connection closed.
Explanation of the Key Classes and Methods
| Class or Method | Role in the Program |
|---|---|
ServerSocket(1254) | The listener: binds the server to port 1254 and waits for connection requests |
accept() | Blocks until a client connects, then returns a Socket for that one client |
Socket("localhost", 1254) | The client end: opens a TCP connection to the server's listening port |
getInputStream() and getOutputStream() | Give the byte streams of the connection, wrapped here in a BufferedReader and a PrintWriter |
PrintWriter(..., true) | The true turns on auto flush, so OK, ERROR and each line of the file leave the socket immediately |
readLine() | Reads one line of the command from the client, and on the client side reads the response and the file |
File.exists() and File.isFile() | Confirm that the requested name refers to an existing ordinary file in the current directory |
close() | Releases the streams and tears the connection down, which also signals end of file to the client |
The protocol works because the client knows how to interpret what it reads. The first line is always the status word, so the client reads exactly one line, compares it with OK, and only then treats every remaining line up to end of stream as file content. Closing the socket on the server is what makes the client's readLine() return null and end the loop, so no explicit length or terminator has to be sent.
Limitations and Possible Improvements
The server handles one client at a time, because the whole exchange happens inside the accept() loop; wrapping the per client code in a Thread (or handing it to a thread pool) lets several clients be served concurrently. Reading with FileReader and writing with PrintWriter also assumes a text file, so a binary file such as an image would be corrupted; using FileInputStream with OutputStream.write() on a byte buffer transfers any file type unchanged. Finally, the file name arrives from the network and is used as it stands, so a name containing a path such as ../secret.txt would escape the intended folder; the question assumes there are no subdirectories, but a real server should reject any name containing a separator before opening it.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.