|
| 1 | +package cs455.mstoverlay; |
| 2 | + |
| 3 | +import java.io.*; |
| 4 | +import java.net.ServerSocket; |
| 5 | +import java.net.Socket; |
| 6 | + |
| 7 | +public class Registry { |
| 8 | + private ServerSocket goodListener; |
| 9 | + |
| 10 | + public Registry(int port) throws IOException { |
| 11 | + goodListener = new ServerSocket(port); |
| 12 | + System.out.println("YAY connection"); |
| 13 | + initiateConnectionAndMaxConnectionTime(); |
| 14 | + } |
| 15 | + |
| 16 | + /** |
| 17 | + * Accepts up to 15 client connections, sends a welcome message, |
| 18 | + * and enforces a maximum connection time before closing. |
| 19 | + */ |
| 20 | + private void initiateConnectionAndMaxConnectionTime() throws IOException { |
| 21 | + // Accept up to 15 client connections |
| 22 | + for (int i = 0; i < 15; i++) { |
| 23 | + Socket clientSocket = goodListener.accept(); |
| 24 | + System.out.println("Accepted connection #" + (i + 1) + " from " + clientSocket.getInetAddress()); |
| 25 | + |
| 26 | + // Send a welcome message to the client |
| 27 | + PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); |
| 28 | + out.println("Hello!" + (i + 1)); |
| 29 | + |
| 30 | + // Track when this connection started |
| 31 | + long connectionStart = System.currentTimeMillis(); |
| 32 | + long maxDuration = 90 * 1000; // 90 seconds in milliseconds |
| 33 | + |
| 34 | + // Read messages until timeout or disconnect |
| 35 | + BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); |
| 36 | + String clientMessage; |
| 37 | + while ((clientMessage = in.readLine()) != null) { |
| 38 | + System.out.println("Client #" + (i + 1) + " said: " + clientMessage); |
| 39 | + |
| 40 | + // Check elapsed time |
| 41 | + long elapsed = System.currentTimeMillis() - connectionStart; |
| 42 | + if (elapsed > maxDuration) { |
| 43 | + System.out.println("Closing connection for Client #" + (i + 1) + " after 30 seconds."); |
| 44 | + break; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + // Close the connection |
| 49 | + clientSocket.close(); |
| 50 | + } |
| 51 | + |
| 52 | + System.out.println("Reached max of 15 connections. Closing server..."); |
| 53 | + goodListener.close(); |
| 54 | + } |
| 55 | + |
| 56 | + public static void main(String[] args) { |
| 57 | + try { |
| 58 | + new Registry(5008); |
| 59 | + } catch (IOException e) { |
| 60 | + e.printStackTrace(); |
| 61 | + } |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | + |
| 66 | + |
| 67 | + |
0 commit comments