5COSC022W.
2 Client-Server Architectures
Tutorial Week 04: Socket Programming
EXERCISE 1: LOGGING
In this tutorial, you will enhance tutorial Week 03 exercise 2 chat application by adding
logging functionalities. Logging is an essential aspect of software development as it
helps in tracking the application's behavior, debugging issues, and maintaining records
of events. We will use java.util.logging.Logger to log messages and save them to a file for
future reference.
STEP 1 – IMPORT THE PROJECT
Import the zip file from the 2nd exercise of tutorial week 3 into your IDE. This will provide
you with the base code for the client-server chat application.
STEP 2 - SET UP LOGGING
Add Logger to Classes: In each class (e.g., SimpleChatClient and SimpleChatServer),
import java.util.logging.Logger and create a Logger instance.
STEP 3 - SET UP FILEHANDLER
Configure a FileHandler to save logs to a text file. This should be done in a static block
to ensure it is set up when the class is loaded.
static {
try {
FileHandler fileHandler = new FileHandler("logs.txt", true);
logger.addHandler(fileHandler);
} catch (IOException e) {
logger.log(Level.SEVERE, "Failed to set up file handler for
logger", e);
}
}
STEP 3- CONFIGURE THE LOGGER
• Specify Log File Name: Use FileHandler to specify the log file name and set it to
append mode.
• Format Log Messages: Use SimpleFormatter to format the log messages for
readability.
• Add FileHandler to Logger: Attach the FileHandler to the Logger instance.
STEP 4 - ADD LOGGING STATEMENTS
• Log Informational Messages: Add logging statements at key points in your code to
log informational messages. For example, log when the server starts, when a client
connects, and when messages are sent or received.
• Log Exceptions: Use logger.log(Level.SEVERE, "message", exception) to log
exceptions.
STEP 5 - TEST THE APPLICATION
• Run the Server and Client Applications: Start the server application first, then run
the client application to connect to the server.
• Check the Log Files: Verify that the log files (logs.txt) are created and contain the
expected log messages. This will help you ensure that all relevant events are being
logged.
EXERCISE 2 – HTTP SERVER
In this exercise, you will learn how to build a basic HTTP client-server application in
Java. The server will handle incoming HTTP GET requests and send back a simple text
response. The client will send a GET request to the server and print the server's
response.
PROJECT STRUCTURE
Please create a new project and call it as Tutorial-week04-EX2. Then, create two Java
files:
1. MyHttpServer.java: Contains the code for the HTTP server.
2. MyHttpClient.java: Contains the code for the HTTP client.
STEP 1: CREATE THE SERVER CLASS AND MAIN METHOD
STEP 2: CREATE THE HTTPSERVER INSTANCE
STEP 3: CREATE THE HTTPHANDLER (INNER CLASS)
STEP 4: IMPLEMENT REQUEST HANDLING IN A SEPARATE THREAD
STEP 5: IMPLEMENT REQUEST PROCESSING AND RESPONSE
Please include the following codes insdie RequestHandlerThread class:
@Override
public void run() {
try {
// Get request information
String requestMethod = exchange.getRequestMethod();
URI requestURI = exchange.getRequestURI();
Headers requestHeaders = exchange.getRequestHeaders();
// Display request information
System.out.println("\n=== INCOMING REQUEST ===");
System.out.println("Method: " + requestMethod);
System.out.println("URI: " + requestURI);
System.out.println("Headers:");
printHeaders(requestHeaders);
// Prepare response with request information
StringBuilder responseContent = new StringBuilder();
responseContent.append("Request Details:\n");
responseContent.append("Method:
").append(requestMethod).append("\n");
responseContent.append("URI:
").append(requestURI).append("\n");
responseContent.append("Headers:\n");
requestHeaders.forEach((key, value) ->
responseContent.append(key).append(":
").append(value).append("\n"));
responseContent.append("\nHandled by thread:
").append(Thread.currentThread().getName());
String response = responseContent.toString();
// Get response headers
Headers responseHeaders = exchange.getResponseHeaders();
// Send response
exchange.sendResponseHeaders(200,
response.getBytes().length);
// Display response information
System.out.println("\n=== OUTGOING RESPONSE ===");
System.out.println("Status: 200 OK");
System.out.println("Headers:");
printHeaders(responseHeaders);
System.out.println("Body length: " +
response.getBytes().length + " bytes");
// Send response body
try (OutputStream os = exchange.getResponseBody()) {
os.write(response.getBytes());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
exchange.close();
}
}
STEP 6: IMPLEMENT PRINTHEADERS METHOD
STEP 7: CREATE A CONTEXT AND START THE SERVER
STEP 8: CREATE THE CLIENT CLASS AND MAIN METHOD
STEP 9: CREATE THE URL AND OPEN A CONNECTION
STEP 10: IMPLEMENTING PRINT HEADER METHOD
STEP 11: GET AND DISPLAY DEFAULT REQUEST HEADERS
STEP 12: SET THE REQUEST METHOD AND GET THE RESPONSE CODE
STEP 13:
STEP 14: RUN AND TEST THE PROGRAM
RUNNING THE SERVER
1. Right-click on MyHttpServer.java in the Projects window.
2. Select "Run File."
3. The server will start, and you should see the "Server starting on port 8080" message
in the Output window (usually at the bottom).
RUNNING THE CLIENT
1. Right-click on MyHttpClient.java in the Projects window.
2. Select "Run File."
3. A new Output window will appear, showing the client's output, including the
response code and the server's message.
STEP 15: TEST THE PROGRAM IN A WEB BROWSER
Open a browser and go to http://localhost:8080/hello). The browser will interact with
your server running from within NetBeans.
STEP 16: OBSERVING OUTPUT
• Server Output: When the server receives a request (either from MyHttpClient or
from the web browser), you will likely see some additional output in the server's
terminal or NetBeans Output window, indicating that a request has been handled.
You might also see the thread name printed as part of the response string.
• Client Output: The MyHttpClient program will print the response code and the
response message to its console (either the terminal or the NetBeans Output
window).
• Web Browser: The web browser will display the server's response message in the
browser window.