============================================================ IT6003 - Advanced Java Programming Lab Session 6: Networking & Design Patterns State University of Zanzibar (SUZA) ============================================================ OBJECTIVES: - Understand TCP client-server communication - Build multi-threaded server applications - Use URL and HttpURLConnection for HTTP requests - Implement common design patterns in Java ============================================================ PART A: TCP Networking [30 minutes] ============================================================ Exercise 1: Simple Echo Server/Client ----------------------------------------- Server (EchoServer.java): a) Create ServerSocket on port 5000. b) Accept a client connection. c) Read message from client using BufferedReader(InputStreamReader(socket.getInputStream())). d) Echo it back using PrintWriter(socket.getOutputStream(), true). e) Repeat until client sends "bye". Client (EchoClient.java): a) Create Socket("localhost", 5000). b) Read user input from Scanner. c) Send to server using PrintWriter. d) Read response from server using BufferedReader. e) Print response. Exit on "bye". Exercise 2: Multi-Client Server ----------------------------------- a) Modify EchoServer to handle multiple clients using threads. b) Accept connections in a loop. c) For each connection, create a new ClientHandler thread. d) ClientHandler implements Runnable, handles one client's communication. e) Test with 3 terminal windows connecting simultaneously. Exercise 3: Chat Application ------------------------------- Server (ChatServer.java): a) Maintain Set of all connected client output streams. b) When a message arrives from any client, broadcast to ALL clients. c) Handle client disconnection (remove from set, close streams). Client (ChatClient.java): a) Two threads: one for reading server messages, one for user input. b) Display received messages with sender name. c) Support /quit command to disconnect. ============================================================ PART B: HTTP and URLs [30 minutes] ============================================================ Exercise 4: URL Parsing -------------------------- a) Create URL object from "https://api.github.com/users/octocat". b) Print: protocol, host, port, path, query. c) Open HttpURLConnection. d) Print: response code, content type, content length. e) Read response body line by line using BufferedReader. f) Print first 500 characters. Exercise 5: HTTP GET Request ------------------------------- a) Write a method: String httpGet(String urlString) throws IOException b) Open HttpURLConnection, set method to "GET". c) Set timeouts: setConnectTimeout(5000), setReadTimeout(5000). d) Check response code (200 = OK). e) Read full response into a String using StringBuilder. f) Test with a public JSON API. Exercise 6: Simple HTTP Server --------------------------------- Using com.sun.net.httpserver.HttpServer: a) Create server on port 8080. b) Add context "/hello" returning "Hello, World!". c) Add context "/time" returning current date/time as JSON. d) Add context "/echo" that reads query parameter "msg" and returns it. e) Start server and test with browser or curl. ============================================================ PART C: Design Patterns [30 minutes] ============================================================ Exercise 7: Singleton Pattern --------------------------------- a) Create DatabaseConnection class with private constructor. b) Private static instance. c) Public static getInstance() method (lazy initialization). d) Make it thread-safe using synchronized or double-checked locking. e) Add methods: getConnection(), closeConnection(). f) Verify: DatabaseConnection.getInstance() == DatabaseConnection.getInstance(). Exercise 8: Factory Pattern ------------------------------ a) Create interface Shape with double area() and String describe(). b) Create implementations: Circle, Rectangle, Triangle. c) Create ShapeFactory with static method: Shape createShape(String type, double... params). d) Factory creates appropriate shape based on type string. e) Test: Shape s = ShapeFactory.createShape("circle", 5.0); Exercise 9: Observer Pattern ------------------------------- a) Create interface Observer with void update(String event, Object data). b) Create class EventManager (Subject/Observable): - Map> listeners - subscribe(String eventType, Observer o) - unsubscribe(String eventType, Observer o) - notify(String eventType, Object data) c) Create concrete observers: EmailNotifier, LogObserver, DisplayObserver. d) Create ProductStore that uses EventManager. e) When price changes or new product added, notify all observers. Exercise 10: Strategy Pattern --------------------------------- a) Create interface SortStrategy with void sort(int[] array). b) Implement: BubbleSortStrategy, QuickSortStrategy, MergeSortStrategy. c) Create Sorter class with setSortStrategy(SortStrategy) and performSort(int[]). d) Switch strategies at runtime: sorter.setSortStrategy(new QuickSortStrategy()); sorter.performSort(data); e) Add timing to each strategy. Print performance comparison. ============================================================ PART D: Integration Challenge [30 minutes] ============================================================ Exercise 11: Networked Student Lookup ----------------------------------------- Combine networking and design patterns: a) Server: Singleton database connection, loads students from file. b) Server: Factory pattern for handling different request types (SEARCH, ADD, DELETE, LIST). c) Client sends request type and parameters. d) Server processes and returns result. e) Observer: Log all requests to a file. Exercise 12: Builder Pattern for HTTP Request ------------------------------------------------- a) Create HttpRequest class with url, method, headers (Map), body, timeout. b) Create HttpRequestBuilder: HttpRequest request = new HttpRequestBuilder("https://api.example.com") .method("POST") .header("Content-Type", "application/json") .body("{\"name\": \"Ali\"}") .timeout(5000) .build(); c) Create HttpClient that executes HttpRequest objects. d) Validate: url is required, method defaults to "GET", timeout defaults to 10000. ============================================================ SUBMISSION: Submit all .java files in a folder named Lab06_RegNo/ ============================================================