Here is an example of how you could create a Java web server to provide weather forecast information to users:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class WeatherForecastServer {
private static final int PORT = 8080;
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("Listening on port " + PORT);
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected");
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(() -> handleClient(clientSocket));
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void handleClient(Socket clientSocket) {
try {
// Read input from client
BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String input = reader.readLine();
// Process input
String weatherForecast = processInput(input);
// Send response to client
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
writer.println(weatherForecast);
writer.flush();
// Close connection
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static String processInput(String input) {
// Replace this with your own implementation to provide weather forecast information
return "Weather forecast: sunny";
}
}
In this example, the server listens on port 8080 and handles incoming requests using a separate thread. When a client connects, the server reads input from the client, processes it, and sends a response back to the client. Finally, the connection is closed.
Note that this is just a basic example and a real-world implementation would require additional error handling, logging, and other features.