-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClientHandlerPart2.java
More file actions
45 lines (37 loc) · 1.55 KB
/
Copy pathClientHandlerPart2.java
File metadata and controls
45 lines (37 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.io.*;
import java.net.*;
// Runnable class to handle individual clients
class ClientHandler implements Runnable {
private final Socket clientSocket;
public ClientHandler(Socket clientSocket) {
this.clientSocket = clientSocket;
}
@Override
public void run() {
try (
InputStream input = clientSocket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
OutputStream output = clientSocket.getOutputStream();
PrintWriter writer = new PrintWriter(output, true)
) {
// Read weight and height from the client
String weightString = reader.readLine();
String heightString = reader.readLine();
double weight = Double.parseDouble(weightString);
double height = Double.parseDouble(heightString);
// Calculate BMI
double bmi = weight / (height * height);
// Send BMI result back to the client
writer.println(String.format("Your BMI is %.2f", bmi));
System.out.println("Processed BMI for client: " + bmi);
} catch (IOException | NumberFormatException e) {
System.err.println("Error handling client: " + e.getMessage());
} finally {
try {
clientSocket.close();
} catch (IOException e) {
System.err.println("Error closing client socket: " + e.getMessage());
}
}
}
}