// Import the necessary libraries
import java.io.*;
import java.net.*;
import java.util.*;
// Define the AI client class
public class AIClient {
// Declare the socket and the input/output streams
private Socket socket;
private BufferedReader input;
private PrintWriter output;
// Define the constructor with the server address and port
public AIClient(String address, int port) {
try {
// Connect to the server
socket = new Socket(address, port);
System.out.println("Connected to the server");
// Initialize the input/output streams
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output = new PrintWriter(socket.getOutputStream(), true);
// Start a new thread to handle the server messages
new ServerHandler().start();
// Read user input from the console and send it to the server
Scanner scanner = new Scanner(System.in);
String userInput;
while ((userInput = scanner.nextLine()) != null) {
output.println(userInput);
}
// Close the scanner and the socket
scanner.close();
socket.close();
} catch (IOException e) {
// Handle any IO exceptions
e.printStackTrace();
}
}
// Define the inner class to handle the server messages
private class ServerHandler extends Thread {
// Override the run method
public void run() {
try {
// Read server messages from the input stream and print them to the console
String serverMessage;
while ((serverMessage = input.readLine()) != null) {
System.out.println(serverMessage);
}
} catch (IOException e) {
// Handle any IO exceptions
e.printStackTrace();
}
}
}
// Define the main method to create an AI client instance
public static void main(String[] args) {
// Check if the arguments are valid
if (args.length != 2) {
System.err.println("Usage: java AIClient <server address> <port number>");
System.exit(1);
}
// Parse the server address and port number from the arguments
String address = args[0];
int port = Integer.parseInt(args[1]);
// Create an AI client instance with the given address and port
AIClient client = new AIClient(address, port);
}
}